2D Lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: 2D Lists (/thread-8655.html) |
2D Lists - garikhgh0 - Mar-02-2018 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. RE: 2D Lists - buran - Mar-02-2018 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_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 RE: 2D Lists - garikhgh0 - Mar-02-2018 thanks |