0
list of list
I want to create a list of list. I know i have five rows and four columns oneRow = [0]*5 ans = [oneRow]*4 print(ans) ans is a matrix of size 5*4 and all elements are 0 as per my expectation. ans[1][2] = 2 This above line should change only second row third element as 2 , but it sets third element of all rows as 2. Please suggest
6 Answers
+ 3
list of list:
ans = [[0]*5 for _ in range(4)]
+ 3
Ketan Lalcheta if you are wondering why it is necessary to use Bob_Li's solution, then this tutorial will help:
https://nedbatchelder.com/text/names.html
It's an easy article to read, and it explains how Python references work.
+ 1
I am Back!
ans = list(oneRow)*4 does not produce a list of list. It's a list of 20 0's.
0
You can use this simpler way one too.
oneRow=[0]*5
ans=list(oneRow)*4
0
Because wen you multiply the list in other list, the list will not be copied. And the lists are binded to each other. Then they must to have the same indexes.