-3
def swap(x, y):
     mylist[x] = mylist[y]

mylist = ["a", "b", "c", "d"]

swap(2, 3)
print(mylist)

So i need to swap two elements in the list with each other but in my code it only replaces not swap. for example it will output as "a b d d" when it shouldn't repeat the same letter twice. it should output as "a b d c" Any helpers?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
afloated_
  • 9
  • 2

3 Answers3

1

You can swap tuples in one step with:

def swap(x, y):
     mylist[x], mylist[y] = mylist[y], mylist[x]

mylist = ["a", "b", "c", "d"]

swap(2, 3)
print(mylist)
# ['a', 'b', 'd', 'c']
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You are never updating mylist[y]. You should run

def swap(x,y):
   assert(x < len(mylist) and y < len(mylist))
   temp = mylist[x]
   mylist[x] = mylist[y]
   mylist[y] = temp
M. Chak
  • 530
  • 3
  • 13
0

You just need to swap the value on the given index, as of now you are doing assignment :-

mylist[x] = mylist[y]

Which is wrong. You are replacing the value of x index with Y index

Correct swap :-

def swap(x,y):
   assert(x < len(mylist) and y < len(mylist))
    mylist[x], mylist[y] = mylist[y], mylist[x] 
Shreeyansh Jain
  • 1,407
  • 15
  • 25