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
3 Antworten
+ 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