Phaml Phaml - 1 month ago 5
Python Question

why list comprehension could select columns of a matrix?why so many down-vote?

Why the list comprehension could select the columns of a matrix? I am a bit confused by the for loop.

m=[[1,2,3],[4,5,6],[7,8,9]]
col=[x for x in m]
col2=col[1]
col2
[4, 5, 6]


Obivious the below codes give the right answer, but why is that? Because in each iteration, the
for loop
takes in a whole row instead of a number?

m=[[1,2,3],[4,5,6],[7,8,9]]
col2=[x[1] for x in m]
col2
[2, 5, 8]]


[update] For those who downvote, do leave a comment on why. Simply a down-vote won't help. Things obvious to you are not so obvious for someone new. The reason I was confused is because I was not clear about the for loop object. Before @heinst pointed out the iteration object is the list element, I thought I understood list-comprehension but I did not.

BTW, I did check what was list comprehension before I ask. I was reading a python book and the book did not explain it well so I came to stack-overflow. Why so hostile to newbie? Is my question not clear enough? Or did I ask some homework problem? I am asking why because I could not figure out. I had check the possible dupe link and was still not clear until @heinst pointed out.

Answer

If you think about it, you are looping over the list and each iteration, x is holding the sub list. You then are getting index 1 of each sub list, which gives you the 2nd column.

Picture it this way:

1, 2, 3

4, 5, 6

7, 8, 9

The bolded items are the items that are accessed in each iteration, and put into a new list, giving you [2, 5, 8]

The expanded list comprehension equivalent is:

col2 = []
for x in m:
    col2.append(x[1])
Comments