0

The general project is to re-build an enigma machine. However, the problem is this: I have a list and I want to rearrange it in a way that the first element is appended to the same list and then the first element is deleted.

Basicly, I want this:

l = [1, 2, 3, 4]

l_new = [2, 3, 4, 1]

for this purpose I constructed the function

def switch_up(list):
    list.append(list[0])
    del list[0]

    return list

The problem: When calling this function with a list, it does not only return the changed list, but changes the original list given as the argument. The full code looks like this:

    def switch_up(list):
        list.append(list[0])
        del list[0]

        return list


    my_list = [1, 2, 3, 4]
    my_list2 = switch_up(my_list)

    print(my_list)
    print(my_list2)

My expected/desired output would be:

[1, 2, 3, 4]
[2, 3, 4, 1]

The output I get is:

[2, 3, 4, 1]
[2, 3, 4, 1]
Ame
  • 35
  • 6

2 Answers2

3

You are altering the list passed into the function. That isn't a copy of the list it's the same list. You should just make a copy and return it with something like:

def switch_up(l):
    # list slices will make shallow copy
    return l[1:] + l[:1]

my_list = [1, 2, 3, 4]
my_list2 = switch_up(my_list)

print(my_list)
# [1, 2, 3, 4]
print(my_list2)
# [2, 3, 4, 1]
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Lists are mutable in python and therefore it is assumed, that you want to do operations on the original list. If you do not want that you have to manually copy your list for example with list.copy. For more information on copy please see this stackoverflow question

All you created is a "pointer" called my_list2 to the same value as my_list if you would for example iclude my_list2[1] = 'a' the result would be:

my_list = [2, 'a', 4, 1]
my_list2 = [2, 'a', 4, 1]

And btw you should never name your variables the same as inbuilt functions, like list

LeoE
  • 2,054
  • 1
  • 11
  • 29