![Python-courses-python-exercises](https://1.bp.blogspot.com/-T3BongcoJFo/X4CftQxVL8I/AAAAAAAAB5U/Lf59WgNyhGo2FdogKqxv0PIy_Ef7XDPdgCLcBGAsYHQ/s0/my-python-courses-python-exercises-with-solutions.png)
Exercise 2
write python algorithm to swap the first element with the last element of given list. Example: if L =
["Python" , "Java" , "C++" , "Javascript"]
, the algorithm returns the list:
["Javascript", "Java" , "C++" , "Python"]
Solution
def swapList(L):
# getting the last element of list
swap = L[-1]
# replace the last element by the first element of list
L[-1] = L[0]
# relace the first element by the last element
L[0] = swap
return L
# Example
L = L = ["Python" , "Java" , "C++" , "Javascript"]
print(swapList(L))
# The output is : ['Javascript', 'Java', 'C++', 'Python']
Younes Derfoufi
my-courses.net
my-courses.net