lists in list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: lists in list (/thread-12254.html) |
lists in list - kubine - Aug-16-2018 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: if I try in this way I get this outputcode: matrix=[] for i in range(3): ++++list=[1] ++++matrix.append(list) print(matrix) matrix[0].append(2) print(matrix)output: why difference beetwen two output? thanks.
RE: lists in list - ichabod801 - Aug-16-2018 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.
|