Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2D Lists
#1
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.
Reply
#2
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
Reply
#3
thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,187 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020