Skip to content
Advertisement

Why can list comprehension select columns of a matrix?

Why can the list comprehension 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]
print col2 # [4, 5, 6]

Obviously 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]
print col2 # [[2, 5, 8]]

Advertisement

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])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement