# Define a 2d Array?

thomas.p.krauss at gmail.com thomas.p.krauss at gmail.com
Mon Oct 13 03:04:48 CEST 2008

```On Oct 11, 9:19 pm, Jillian Calderon <jillian.calde... at gmail.com>
wrote:
> How do I define a 2d list?
>
> For instance, to define a 4 by 5 list, I wanted to do this:
> n=4
> m=5
> world = [n][m]
> However, it gives me an invalid syntax error saying the index is out
> of range.

Here are some examples of how you can use list comprehensions to do
this:

In [1]: n=4

In [2]: m=5

In [3]: world = [[[] for ni in range(n)] for mi in range(m)]

In [4]: world
Out[4]:
[[[], [], [], []],
[[], [], [], []],
[[], [], [], []],
[[], [], [], []],
[[], [], [], []]]

In [5]: world[0][0]
Out[5]: []

In [6]: len(world)
Out[6]: 5

In [7]: len(world[0])
Out[7]: 4

In [8]: world = [[[ni+mi*n] for ni in range(n)] for mi in range(m)]

In [9]: world
Out[9]:
[[[0], [1], [2], [3]],
[[4], [5], [6], [7]],
[[8], [9], [10], [11]],
[[12], [13], [14], [15]],
[[16], [17], [18], [19]]]

Best,
Tom

```

More information about the Python-list mailing list