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?
CodePudding user response:
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']
CodePudding user response:
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
CodePudding user response:
With
mylist[x] = mylist[y]
you only modify mylist[x]
, but mylist[y]
stays the same. Use this instead to modify both simultaneously:
mylist[x], mylist[y] = mylist[y], mylist[y]
You can read more about it in the Python docs about assignment statements: https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
CodePudding user response:
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]