How to initialize a two-dimensional array in Python?

A pattern that often came up in Python was

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME_EXPRESSION for item in some_iterable]

which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.

Your code follows this pattern twice

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /

Leave a Comment