Search code examples
pythonlistpython-2.7

Python list.append function changes previous added member unexpectedly


I'm facing an issue with python as below:

  • I have 2 initial lists:

first_list = [['a1', 'a2'], ['a1', 'a2']]

second_list = ['b1', 'b2']

  • I want to replace "b2" in second_list by each of value from another list, then add it to first_list. For example:

parts = ['C', 'D']

My expected result for first_list will be: [['a1', 'a2'], ['a1', 'a2'], ['b1', 'C'], ['b1', 'D']]

Here is my code:

first_list = [['a1','a2'], ['a1','a2']]
second_list = ['b1','b2']

parts = ['C', 'D']

for record in parts:
    print record    #print to see which value we will use to replace "b2"
    temp = second_list
    temp[1] = record
    print temp      #print to see which value will be appended to first_list
    first_list.append(temp)
    print first_list     #print first_list after adding a new member

And the result is:

C
['b1', 'C']
[['a1', 'a2'], ['a1', 'a2'], ['b1', 'C']]
D
['b1', 'D']
[['a1', 'a2'], ['a1', 'a2'], ['b1', 'D'], ['b1', 'D']]

I suspect that something is wrong but can't explain it. Replacing "append" by "insert" function still shows the same issue. Could someone help me?

Thanks


Solution

  • the thing is that you copy just reference in this step temp = second_list

    so the temp is actually the same thing as second_list

    you have to copy the values which you can do for example like this temp = second_list[:] it will create new list and it should work