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

25th Dec 2024, 11:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Respuestas
+ 3
list of list: ans = [[0]*5 for _ in range(4)]
25th Dec 2024, 2:05 PM
Bob_Li
Bob_Li - avatar
+ 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.
25th Dec 2024, 8:04 PM
Brian
Brian - avatar
+ 2
Thanks Bob_Li nd Brian
26th Dec 2024, 4:33 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
I am Back! ans = list(oneRow)*4 does not produce a list of list. It's a list of 20 0's.
27th Dec 2024, 3:40 AM
Bob_Li
Bob_Li - avatar
0
You can use this simpler way one too. oneRow=[0]*5 ans=list(oneRow)*4
27th Dec 2024, 3:30 AM
MaziarDX
MaziarDX - avatar
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.
27th Dec 2024, 3:31 AM
MaziarDX
MaziarDX - avatar