Why can the list comprehension select the columns of a matrix? I am a bit confused by the for-loop.
JavaScript
x
5
1
m = [[1,2,3],[4,5,6],[7,8,9]]
2
col = [x for x in m]
3
col2 = col[1]
4
print col2 # [4, 5, 6]
5
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?
JavaScript
1
4
1
m = [[1,2,3],[4,5,6],[7,8,9]]
2
col2 = [x[1] for x in m]
3
print col2 # [[2, 5, 8]]
4
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:
JavaScript
1
4
1
col2 = []
2
for x in m:
3
col2.append(x[1])
4