0

How can we swap objects in a list in python

What is the function meant for swapping objects in an array

21st Jul 2020, 2:03 PM
Dhananjay Pai
Dhananjay Pai - avatar
9 Respuestas
+ 3
You can do swapping by the following method : List=['a', 'b','c', 'd'] temp=List[0] List[0]=List[3] List[3]=temp print(List) Output:['d','b','c','a'] I have just exchanged 'a' and 'd'. I hope, this will help you.
21st Jul 2020, 3:10 PM
Jaya Singh
Jaya Singh - avatar
+ 2
Dhananjay Pai i=["sun","moon","dog","stick","parabola"] i[0] , i[2] = i[2] , i[0] #swapping print(i) #Output= [dog,moon,sun,stick, parabola]... If you don't know index of "sun", then get it by Index = i.index("sun") then, i[Index] i means input list of your code.....
21st Jul 2020, 3:07 PM
Jayakrishna 🇮🇳
+ 1
Dhananjay Pai I want to add one more simpler method to reverse a list: s=["sun","moon","dog"] s.reverse() If you want to use swapping, you can use the random module with random.shuffle[ ] or random. choice[ ]
21st Jul 2020, 2:19 PM
Arctic Fox
Arctic Fox - avatar
0
Input =[sun,moon,dog] Output=[dog,moon,sun]
21st Jul 2020, 2:12 PM
Dhananjay Pai
Dhananjay Pai - avatar
0
Aree if input=[sun,moon,dog,stick,parabola] Output= [dog,moon,sun,stick, parabola]
21st Jul 2020, 2:16 PM
Dhananjay Pai
Dhananjay Pai - avatar
0
I just shuffled dog and sun all remaining are same
21st Jul 2020, 2:27 PM
Dhananjay Pai
Dhananjay Pai - avatar