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
2 ответов
+ 1
list of list:
ans = [[0]*5 for _ in range(4)]
+ 1
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.