You iterate through the rows and take second element of the row. Then you collect the extracted elements from the rows. It means that you have extracted the column.
Read the list comprehension from the right to the left. It says:
- Loop through the matrix
M
to get the row
each time (for row in M
).
- Apply the expression to the
row
to get what you need (here row[1]
).
- Iterate through the constructed results and build the list of them (
[
...]
).
The last point makes it the list comprehension. The thing between the [
and ]
is called a generator expression. You can also try:
column = list(row[1] for row in M)
And you get exactly the same. That is because the list()
construct a list from any iterable. And the generator expression is such iterable thing. You can also try:
my_set = set(row[1] for row in M)
to get the set of the elements that form the column. The syntactically brief form is:
my_set = {row[1] for row in M}
and it is called set comprehension. And there can be also a dictionary comprehension like this:
d = { row[1]: True for row in M }
Here rather artificially, the row[1]
is used as the key, the True
is used as the value.