Home > OS >  Making a definition that doesn't modify the input of a list when switched?
Making a definition that doesn't modify the input of a list when switched?

Time:10-26

I’m trying to shift the first and second characters without the input being modified, but because I’m using holder to hold the input seems to be modified, does anyone know another way of doing this which wouldn’t modify it?

shiftlist = ['a', 'b', 'c']


def switch(shiftlist):
    holder = shiftlist[0]
    shiftlist[0] = shiftlist[1]
    shiftlist[1] = holder
    return shiftlist

CodePudding user response:

You can pass a copy of the list instead of the list itself.

print(switch(shiftlist.copy()))
print(shiftlist)
['b', 'a', 'c']
['a', 'b', 'c']

CodePudding user response:

Firstly, read List changes unexpectedly after assignment. Why is this and how can I prevent it?

Now, this case is a bit different because it's a function. Passing an argument does an implicit assignment to the parameter name in the function scope.

One option is to pass in a copy (like in Stuart's answer), but that means the input list would get modified and returned, which is unconventional. Instead, make a copy inside the function.

def switch(shiftlist):
    new = shiftlist.copy()
    new[0], new[1] = new[1], new[0]  # BTW, no temporary variable needed
    return new

L = ['a', 'b', 'c']
print(switch(L))  # -> ['b', 'a', 'c']
print(L)  # -> ['a', 'b', 'c']
  • Related