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 !
-
Python pour Excel: Automatisation et Analyse des Données
€ 34,00 Acheter le livre -
Disque dur EMTEC SSD Interne X150 240 Go- Prix Abordable
€ 21,00 Acheter le produit -
Répéteur WiFi,1200Mbps Dual Band 2.4G / 5G WiFi Amplifier,WiFi Signal Booster,2 Ports LAN ,4 Antennes,WiFi Extenders
€ 18,00 Acheter le produit
1 thought on “Solution Exercise 2: python algorithm that swaps the first element of a list with the last”