-2

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]

Syed Naqi
  • 37
  • 7
  • `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
  • 1
    Is 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 Answers1

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