In my previous post, I covered How to use map, filter and reduce in Python.
Here I demonstrate how to use a List comprehension to achieve similar results to using map
and filter
together.
You can use a list comprehension to iterate over an iterable, like a string, list or tuple and create new list,
Basic
The simplest kind does nothing.
a = [1, 2, 3]
b = [x for x in a]
b
# [1, 2, 3]
Map style
Here we apply something like the map
call.
a = [1, 2, 3]
b = [x**2 for x in a]
b
# [1, 4, 9]
Note you don't need a lambda.
If you had a function, you would use it like this:
b = [square(x) for x in a]
b
# [1, 4, 9]
Using a string instead of a list
.
c = 'aBcD'
c.isupper()
# False
[x for x in c if x.isupper()]
# ['B', 'D']
Filter style
This is a way to an if
statement inside the list comprehension to filter out values.
a = [1, 2, 3]
[x for x in a if x > 2]
# [3]
[x for x in a if x > 1]
# [2, 3]
[x**2 for x in a if x > 1]
# [4, 9]
Map and filter combined
You can use the map
and filter
styles together.
a = [1, 2, 3]
[x**2 for x in a if x > 2]
# [9]
[x**2 for x in a if x**2 > 2]
# [4, 9]
Generator
As a bonus, you can use a list comprehension as a generator if you use round brackets instead of square brackets.
I have hardly need to use this, but if you need to optimize your performance or you are working with large external data in a file or a REST API, you could find this useful. As it reduces how much is processed and stored in memory at once.
Standard:
a = [1, 2, 3]
b = [x**2 for x in a]
[1, 4, 9]
Generator:
c = (x**2 for x in a)
c
# <generator object <genexpr> at 0x1019d0f90>
list(c)
[1, 4, 9]
Or you might use a for
loop to iterate over your initial list
.
Here we chain two generators together. Computation is done lazily - both generators are only evaluated at the end.
c = (x**2 for x in a)
d = (x+1 for x in c)
list(d)
# [2, 5, 10]
That is similar to this, which applies both transformations at once.
d = (x**2 + 1 for x in a)
list(d)
# [2, 5, 10]
Or with function calls.
d = (add_one(square(x)) for x in a)
list(d)
# [2, 5, 10]
Links
See this a post by @kalebu
- A guide to Python list comprehension
Interested in more of my writing on Python? I have 3 main places where I collect Python material that is useful to me.
- Python topic on Learn to Code - good for beginners but the resources list will useful for all levels.
- Python Cheatsheets
- Python Recipes
Here are all my Python repos on GitHub if you want to see what I like to build.
Top comments (0)