Exercise 2
Write a Python algorithm to swap the first element with the last element of a given list. Example: if L = ["Python", "Java", "C++", "Javascript"], the algorithm returns the list: ["Javascript", "Java", "C++", "Python"]
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def swapList(L): # get the last item in the list swap = L[-1] # replace the last item in the list with the first L[-1] = L[0] # replace the first item in the list with the last L[0] = swap return L # Example L=["Python", "Java", "C++", "Javascript"] print(swapList(L)) # Output is: ['Javascript', 'Java', 'C++', 'Python'] |
Younes Derfoufi
CRMEF OUJDA
1 thought on “Solution Exercise 2: python algorithm that swaps the first element of a list with the last”