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
Acheter sur Très Facile !
-
Apprentissage de la machine: La révolution des neurones artificiels et de l'apprentissage profond
€ 23,00 Acheter le livre -
Mon Pense-Bête PHP : Un Guide Complet pour le Développement Web
€ 12,00 Acheter le livre -
Lecteur CD/DVD Externe Cocopa USB 3.0 : Graveur Enregistreur Portable RW/ROM
€ 26,00 Acheter le produit
1 thought on “Solution Exercise 2: python algorithm that swaps the first element of a list with the last”