Help with lists?

Can someone please uncompress this line and tell me how it works?

grid = [[0 for x in range(22)] for y in range(22)]

Is this a list of lists or a pair of lists or what? It appears to create what in languages of the past I would call a two-dimensional array. Addressing this object takes the form

grid[1][1] = 1
or
print(grid[99][99])

So the indexing is familiar, but I don’t understand what the thing is, exactly.

Thanks, Ig.

Something that may be useful is to pretty-print anything you’re not comfortable with the structure of

import json
print(json.dumps(grid, indent=4))
import pprint
pprint.pprint(grid)

Hi Igor,

Your Python guy used:

grid = [[0 for x in range(22)] for y in range(22)]

Let’s unpack it. The outer list is what we call a comprehension:

[THING for y in range(22)]

A list comprehension is a short-cut for a for-loop:

grid = []
for y in range(22):
    grid.append(THING)

only a bit more efficient.

The inner list, THING, is another list comprehension:

# THING above
[0 for x in range(22)]

So we can unpack the lot as:

grid = []
for y in range(22):
    temp = []
    for x in range(22):
        temp.append(0)
    grid.append(temp)

Please feel free to ask further questions if that isn’t clear.

1 Like

Very clear, perfectly explained.

Beautiful code, too.

Thank you.