I am trying to create nested list of arbitruary size N X M
assume N = 3, M = 3 when I create a list like this
c = [0 for col in range(N)]
c = [c for r in range(M)]
print c
and execute
c[0][0]=1
I get
c = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
But when I create a list like this:
c = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
and execute
c[0][0] = 1
I get
c = [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
I am new in python, can somebody give me some idea ?
In list comprehension, you are creating a reference to every element in the list. That means that every element will be mutated when only one index is accessed and updated.
c = [0 for col in range(3)]
c = [c for r in range(3)]
c[0][0] = "Test"
Output:
[['Test', 0, 0], ['Test', 0, 0], ['Test', 0, 0]]
Edit:
A nested list of arbitrary size:
import random
new_list = [[0 for i in range(random.randint(1, 10))] for b in range(random.randint(1, 10))]
Output:
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0], [0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]