List comprehensions apply an arbitrary expression to items in an iterable, rather than applying a function.
List comprehensions and
for loops are the most prominent contexts in which the iteration protocol is applied.
The list comprehension expression makes many coding patterns, you may be used with, obsolete. In the example below, we can replace the loop with a single expression that produces the desired result.
>>> L1 = [1, 2, 3, 4] >>> for i in range(len(L1)): ... L1[i] += 10 ... >>> L1 [11, 12, 13, 14]
>>> L1 = [1, 2, 3, 4] >>> L1 = [x + 10 for x in L1] >>> L1 [11, 12, 13, 14]
The result is similar, but it requires less coding and runs faster.
List comprehensions are written in square brackets because they are a way to construct a new list.
If you take as example the above list comprehension then we have:
L1 = [x + 10 for x in L1]
They begin with an arbitrary expression, which uses a loop variable (in our case it is
x + 10). Then we have the header of a
for loop (the
for x in L1 part).
x to each item in turn then collects the result, which is as we expected, a new list containing
x + 10 , for every
List comprehensions can also be used on files. The file object has a
readlines() method that loads the file into a list of line strings all at once:
>>> f = open('text.txt') >>> lines = f.readlines() >>> lines ['Hi there!\n', 'My name is Dan!\n', 'Hey, I am a developer.\n']
What we want is to get rid of the
\n at the end of the row.
>>> lines = [line.rstrip() for line in lines] >>> lines ['Hi there!', 'My name is Dan!', 'Hey, I am a developer.']
rstrip() method removes the whitespace from the right side of a row.
The file will be read line by line because the list comprehension will automatically use the iteration
protocol. Basically, we get the
rstrip() result of a line, for every line in the file.
We can run any string operation on the file’s lines as we iterate.
>>> [line.upper() for line in lines] ['HI THERE!', 'MY NAME IS DAN!', 'HEY, I AM A DEVELOPER.'] >>> [line.replace(' ', '...') for line in lines] ['Hi...there!', 'My...name...is...Dan!', 'Hey,...I...am...a...developer.'] >>> [line.split() for line in lines] [['Hi', 'there!'], ['My', 'name', 'is', 'Dan!'], ['Hey,', 'I', 'am', 'a', 'developer.']]
for loop nested in a comprehension expression can have an
if clause to filter out the result items for which the test is not true.
For example, if we need to collect only lines that begin with the letter ‘H’, we can add an
if filter clause.
>>> lines = [line.rstrip() for line in open('text.txt') if line == 'H'] >>> lines ['Hi there!', 'Hey, I am a developer.']
Here is another example of list comprehension that contains an
>>> square_nums = [i ** 2 for i in range(5)] >>> print(square_nums) [0, 1, 4, 9, 16] >>> even_nums = [i ** 2 for i in range(5) if i ** 2 % 2 == 0] >>> print(even_nums) [0, 4, 16]List comprehensions can contain nested loops (any number of nested
forclauses) and each of them can have
>>> [x + y for x in 'dan' for y in 'dum'] ['dd', 'du', 'dm', 'ad', 'au', 'am', 'nd', 'nu', 'nm']