简体   繁体   中英

Why does Python list of lists behave differently depending on their declaration?

I am trying to create a list inside another list in Python. I noticed that depending on the declaration the final (outer) list behaves differently.

I tried to create list of lists in two different ways. Both cases gave me varies results.

#Case 1
def test():
    lt1 = lt2 = list()
    for i in range(0, 10):
        for j in range(0, 2):
            lt1.append(j);
        lt2.append(lt1);
        lt1 = [];
    print (lt2)

if __name__ == "__main__":
    test()
#Case 2
def test():
    lt1 = list()
    lt2 = list()
    for i in range(0, 10):
        for j in range(0, 2):
            lt1.append(j);
        lt2.append(lt1);
        lt1 = [];
    print (lt2)

if __name__ == "__main__":
    test()

In case 1 the output is [0, 1, [...], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]

In case 2 the output is [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] which is the expected answer for my implementation.

I wanted to know why the first code snippet acts differently.

It's because of the first line:

>>> a = b = []
>>> a
[]
>>> b
[]
>>> a is b
True
>>> a = []
>>> b = []
>>> a is b
False
>>> 

With one line as in case 1, it contains the same object, so:

>>> a = b = []
>>> a.append(1)
>>> a
[1]
>>> b
[1]
>>> 

Which doesn't happen with two lines:

>>> a = []
>>> b = []
>>> a.append(1)
>>> a
[1]
>>> b
[]
>>> 

So simply because the first line of case 1 has a and b that are the exact same objects, unlike the second case's fist line, that are same values, but different id ( id(a) == id(b) is the same as a is b ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM