Python Forum

Full Version: 2D Lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. I have a question on 2D lists or 2D arrays.

So, if there is need beforehand to declare one of the above mentioned, how to aproach to it. As it is unknown how many rows and columns are in the list/array.
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.

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_list
same 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
thanks