Skip to main content

9.9) List Comprehension Uses


A list comprehension always produces a list, but can work on any sequence. For example, here we loop through the string alphabet.

>>> alphabet='abcde'
>>> double_alphabet= [char*2 for char in alphabet]
>>> double_alphabet
['aa', 'bb', 'cc', 'dd', 'ee']

Here’s another handy use of a list comprehension; getting the row of a matrix-like nested list:

>>> M=[[1,2,3],
       [4,5,6],
       [7,8,9]]
>>> col2=[row[1] for row in M]    # select 2nd column of M
>>> col2
[2, 5, 8]

To understand this, check the Python Tutor visualisation for this example:

(If the animation doesn't load, click this link to see it at pythontutor.com.)