unexpected behaviour of nested lists in python

前端 未结 1 1297
天命终不由人
天命终不由人 2021-01-27 02:09

I have a nested list called basic and I want to change one of its entries. I had assumed the following behaviour:

expected = [ [9],[0] ]
unexpected         


        
1条回答
  •  春和景丽
    2021-01-27 03:02

    In your first example:

    basic = [ [0],[0] ]
    

    you have created a list object containing two different list objects. You can see that they are different objects via id() or identity:

    assert id(basic[0]) != id(basic[1])
    
    assert basic[0] is not basic[1]
    

    In your second example:

    l = [0]
    modified = [ l, l ]
    

    you have placed the same list object into another list two times. Both list indicies refer to the same object:

    assert id(basic[0]) == id(basic[1])
    
    assert basic[0] is basic[1]
    

    So, yes. This is how variables (and the objects they point to) work in Python.

    To get the expected behavior, you need to create separate list objects:

    modified = [ l.copy(), l.copy() ]
    

    0 讨论(0)
提交回复
热议问题