[Python] Python list.append function changes previous added member unexpectedly [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página