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.

JavaScript

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

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