How to initialize a two-dimensional array in Python?

How to initialize a two-dimensional array in Python?

A pattern that often came up in Python was

How to initialize a two-dimensional array in Python?

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)                           /

Dont use [[v]*n]*n, it is a trap!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

but

    t = [ [0]*3 for i in range(3)]

works great.

How to initialize a two-dimensional array in Python?

You can use a list comprehension:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of foo (which can depend on i and j if you want)

Leave a Reply

Your email address will not be published. Required fields are marked *