Python Forum

Full Version: lists in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi I make a list in list and append in [0] index a value. but it appends in all index. can andybody know why?
code:
matrix=[[1]]*3
print(matrix)
matrix[0].append(2)
print(matrix)
output:
Output:
[[1], [1], [1]] [[1, 2], [1, 2], [1, 2]]
if I try in this way I get this output
code:
matrix=[]
for i in range(3):
++++list=[1]
++++matrix.append(list)
print(matrix)
matrix[0].append(2)
print(matrix)
output:
Output:
[[1], [1], [1]] [[1, 2], [1], [1]]
why difference beetwen two output? thanks.
Lists are mutable. When you copy them with [[3]] * 3 it copies three references to the same list. Use a list comprehension instead: [[3] for sublist in range(3)]. With a list comprehension, the sub-list is reevaluated each time through the loop, giving you three independent sub-lists.