Reputation: 33
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.
Upvotes: 3
Views: 123
Reputation: 71580
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
).
Upvotes: 2