0
How can we swap objects in a list in python
What is the function meant for swapping objects in an array
9 ответов
+ 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.
+ 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.....
+ 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[ ]
0
Input =[sun,moon,dog]
Output=[dog,moon,sun]
0
Aree if
input=[sun,moon,dog,stick,parabola]
Output= [dog,moon,sun,stick, parabola]
0
I just shuffled dog and sun all remaining are same