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.