Mar-02-2018, 11:13 AM
There is no NEED to declare whatsoever. Probably you mean to initialize the variable with empty list(s). You can always refactor your code to avoid even that.
If you don't know number of elements in the inner list(s) you can always initialize just the outer list as empty one.
If you don't know number of elements in the inner list(s) you can always initialize just the outer list as empty one.
from random import randint my_2D_list = [] num_rows = randint(1,5) num_cols = randint(1,5) for row in range(num_rows): my_2D_list.append([]) for col in range(num_cols): my_2D_list[row].append(randint(1,10)) print my_2D_listsame can be done as
from random import randint num_rows = randint(1,5) num_cols = randint(1,5) my_2D_list = [[randint(1,10) for col in range(num_cols)] for row in range(num_rows)] print my_2D_list