'Can't understand this Python syntax

max_rows = 8
max_cols = 4

matrix = [[1] * max_cols for _ in range(max_rows)]

I can't understand what is happening with this matrix, can someone explain me?



Solution 1:[1]

It's called 'list comprehension'

[1] * max_cols

Creates a list of 1, max_cols times, i.e [1, 1, ..., 1] max_cols times.

[[1] * max_cols for _ in range(max_rows)]

Takes the created list [1, 1, ..., 1] and copies it max_rows times (as if it was in a for-loop).

Note: an interesting question arises: why not just do [[1] * max_cols] * max_rows?

The answer is that [...] * n is replicating the address of [...], n times and as such, each change to one of the arrays (a pointer to [...]) will be seen in all of the arrays

Solution 2:[2]

It's a list comprehension, a way of creating a list.

This is equivalent to :

max_rows = 8
max_cols = 4
matrix = []
for _ in range(max_rows):
    matrix.append([1] * max_cols)

But it is way shorter to write and faster at execution-time.

_ is a way of naming loop variables that are not used.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 imperosol