- In Python, you can often avoid a loop, creating a list directly
with an expression called a list comprehension, which is
likely to be shorter and easier to read than the equivalent loop.
- Consider this function, which takes a list of strings and makes
all of them upper case, returning the new list.
def upper_list(ls):
for i, l in enumerate(ls):
ls[i] = l.upper()
return ls
- We can accomplish the same thing with a single short line using a
list comprehension:
def upper_list(ls):
return [s.upper() for s in ls]
- A list comprehension takes a list and builds another list by
modifying the elements of the original list.
- It uses the same brackets that we expect for a list.
- It begins with an expression that defines each element of the
list being created.
- This is followed by at least one
for
expression, that is, for followed by one or more
variables representing the elements of the original list, followed by in and the
original list.
- This is then followed optionally by one or more
if
expressions that control which elements in the original list are passed on to the
function to be added to the new list.
- Here's another simple example; this starts with a list of sequences of
numbers and yields a list of sums of each subsequence.
[sum(x) for x in sum_list]
- If we want to return all of the elements in a list that satisfy some criterion,
we can just use the identity function for the expression in the first position
and an
if expression to perform the filtering.
[x for x in number_list if x > 3]
- If the original list in the
for expression consists
of sequences, we can bind more than one variable to the elements of
these sequences.
>>> [x + y for x, y in [(2, 3), (5, 8), (9, -1)]]
[5, 13, 8]
- When more than one
for expression is given, the
list that
is returned has an element for each combination of elements in the
original lists (unless an if expression filters out the
elements).
The following example takes lists of pairs representing people -- (name,
age) -- and returns pairs of people whose ages are similar.
[(p1[0], p2[0]) for p1 in group1 for p2 in group2 if abs(p1[1] - p2[1]) < 5]
- Practice
- Write a function that takes a list of numbers and returns a
similar list with all negative numbers
replaced by 0s. (Try this two ways, with
enumerate and
with a list comprehension.)
- Write a function that calculates the dot product (inner
product) of two vectors of numbers
(represented as lists), that is, the sum of the products of
corresponding numbers in the vectors.
Note that the built-in function
sum returns the sum of
the elements in a sequence.