Search code examples
pythonlistappendextend

List.append/extend + operators and +=


I'm having a really hard time trying to understand the behaviour of this code below. In python 3.6

The example code below is an abstraction of my actual code. I have done this to better describe my issue. I'm attempting to add a list to another list. Resulting in a two dimensional list. For the purpose of checking membership, of that list at a later time. Though I can't manage to add my list in the way i'd like Eg.

a_list = []
another_list = [7,2,1]

a_list.DONT_KNOW(another_list)
another_list = [7,3,1]

results:

a_list
[[7,2,1]]
another_list
[7,3,1]

Example of my issue:

class foo:
    def __init__(self):
        self.a_list = []
        self.another_list = [0]
####### Modifying .extend/.append##############
        self.a_list.append(self.another_list) #  .append() | .extend(). | extend([])
###############################################
    def bar(self):
######## Modifying operator########
        self.another_list[0] += 1 #              += | +
###################################
        print('a_list = {} another_list = {} '.format(self.a_list, self.another_list))

def call_bar(f, repeats):
    x = repeats
    while x > 0:
        x -= 1
        foo.bar(f)

f = foo()
call_bar(f,3)

Repeated 5 times. Modifying the list.function and the increment operator. Outputs:

        # .append() and +=
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

        # .extend() and +=
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]

        # .append() and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

        #.extend() and +
a_list = [0] another_list = [1]
a_list = [0] another_list = [2]
a_list = [0] another_list = [3]

        #.extend([]) and +
a_list = [[1]] another_list = [1]
a_list = [[2]] another_list = [2]
a_list = [[3]] another_list = [3]

Notice that in all these examples when I get the two dimensional array (I need). The values in a_list change when manipulating another_list. How do I get the code to do this?

     #SOME METHOD I DON'T KNOW
a_list = [[0]] another_list = [1]
a_list = [[0]] another_list = [2]
a_list = [[0]] another_list = [3]

Solution

  • You have to use self.a_list.append(self.another_list.copy()) to create a snapshot of another_list that is then added to a_list. Your code actually adds another_list as element of a_list, so it is natural that later edits would change the contents of that object.