So I have a problem, I want to swap two item in a list given there index of the first integer we will swap it with the integer that follows it. How can I do this, So here is an example: swap[1,2,3,4], index = 0; result = [2,1,3,4]
Asked
Active
Viewed 1,183 times
-2
-
`your_list[index], your_list[index + 1] = your_list[index + 1], your_list[index]` – Delgan Nov 14 '15 at 12:18
-
I tried using that but the problem I'm having is that it doesn't add to the list and it prints that old list – Syed Naqi Nov 14 '15 at 12:27
-
1Is this a question from some sort of assignment? This [very same question](http://stackoverflow.com/questions/33707997/swapping-list-with-index) has been asked here several times the last couple hours. – Lukas Graf Nov 14 '15 at 12:29
1 Answers
0
list=[1,2,3,4]
i=0 #your index
if i==(len(list)-1):
j=0
else:
j=i+1
list[i], list[j] = list[j], list[i]
if you are not sure of the index and want to swap by a specific value on the list use i=list.index("2")

m0bi5
- 8,900
- 7
- 33
- 44
-
-
-
Also I just have one more concern If the index is that of the last position like the last element I want to swap it with the first element in the list how can I do that so for ex: my_list = [1,2,3,4] index = 3 result = [4,2,3,1] can you tell me how can I do that. – Syed Naqi Nov 14 '15 at 12:42
-
-
-
-
-
-
-
-
it works but instead of swapping the first and last element is swaps the other elements – Syed Naqi Nov 14 '15 at 14:24
-
-
-