Contents
Learn in-demand programming skills and become a certified Python Developer with the Treehouse Techdegree Program. Start your free seven days of learning now.
Simplify Your Python Loops
If you’re like most programmers, you know that once you have a collection of data, you’re going to need to write a loop. Most of the time, this is straightforward, but sometimes you want a more concise way to accomplish simple tasks.
Thankfully, Python provides an awesome tool: Comprehensions. In this blog, we’ll explore how to simplify your loops using comprehensions, along with the latest best practices.
What Are Comprehensions?
Comprehensions are constructs that allow you to generate a new collection in a concise, readable way by embedding loops and conditional logic directly within the collection’s definition. The most commonly used comprehension is the list comprehension, but similar constructs exist for dictionaries, sets, and generators.
Here’s the basic structure of a list comprehension:
[expression for item in iterable]
Let’s explore how to use list comprehensions with an example.
Doubling Values in a List
Suppose we want to double the values of all items in a list. First, let’s write a traditional function to achieve this:
my_list = [21, 2, 93]
def list_doubler(lst):
doubled = []
for num in lst:
doubled.append(num * 2)
return doubled
my_doubled_list = list_doubler(my_list)
print(my_doubled_list) # Output: [42, 4, 186]
While this function works, it’s unnecessarily verbose for such a simple task. Let’s rewrite it using a list comprehension:
def list_doubler(lst):
return [num * 2 for num in lst]
my_doubled_list = list_doubler(my_list)
print(my_doubled_list) # Output: [42, 4, 186]
Now the function is much more concise and easier to read. The list comprehension directly creates the new list by iterating over lst
and applying the num * 2
operation to each element.
Why Use Comprehensions?
List comprehensions and other types of comprehensions:
- Save Space: Reduce boilerplate code and improve readability.
- Performance: In many cases, they’re faster than manually appending to a list due to Python’s optimized implementation. However, it’s important to note that in some specific cases, traditional loops might be slightly more performant.
- Clarity: Keep the logic inline, which makes simple operations easier to understand at a glance.
Adding Conditional Statements
Comprehensions become even more powerful when combined with conditional logic. For example, let’s write a function that filters a list to only include words longer than 5 characters:
Traditional Loop:
def long_words(lst):
words = []
for word in lst:
if len(word) > 5:
words.append(word)
return words
print(long_words(['blog', 'Treehouse', 'Python', 'hi']))
# Output: ['Treehouse', 'Python']
Using a List Comprehension:
def long_words(lst):
return [word for word in lst if len(word) > 5]
print(long_words(['blog', 'Treehouse', 'Python', 'hi']))
# Output: ['Treehouse', 'Python']
This approach not only saves space but also keeps the filtering logic closer to the data generation, improving readability.
Beyond Lists: Other Comprehensions
Dictionary Comprehensions
Dictionary comprehensions allow you to create dictionaries in a concise manner, similar to list comprehensions, by defining key-value pairs within the comprehension.
squares = {num: num**2 for num in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Set Comprehensions
Set comprehensions are used to create sets, which are unordered collections of unique elements. They follow a similar syntax to list comprehensions but utilize curly braces {}
.
unique_lengths = {len(word) for word in ['Python', 'blog', 'Treehouse', 'Python']}
print(unique_lengths) # Output: {8, 4, 9}
Generator Expressions
Generator expressions are memory-efficient because they don’t create the entire list in memory at once:
gen = (num * 2 for num in range(1, 6))
print(list(gen)) # Output: [2, 4, 6, 8, 10]
Tips for Using Comprehensions
- Keep Them Simple: Avoid nesting comprehensions too deeply. If a comprehension becomes hard to read, consider using a traditional loop.
- Example of a poorly nested comprehension:
nested = [[x*y for x in range(3)] for y in range(3)]
- Example of a poorly nested comprehension:
- Use Readable Names: Make sure the variables in your comprehensions are descriptive.
- Leverage Built-In Functions: Combine comprehensions with Python’s built-in functions like
sum()
,max()
, orsorted()
for even more concise code.
Practice Makes Perfect
Here are a few exercises to try:
- Write a list comprehension that extracts all even numbers from a list.
- Use a dictionary comprehension to create a mapping of numbers to their cubes.
- Create a set comprehension that removes duplicates from a list of words.
- Challenge: Using a comprehension, create a list of tuples, where each tuple contains an element from two different lists.
- Challenge: Using a comprehension, flatten a nested list.
Where to Go from Here
Comprehensions are just the beginning. If this has whetted your appetite, explore more advanced topics like:
- Functional Programming: Learn about
map()
,filter()
, andreduce()
. - Advanced Itertools: Dive into Python’s powerful
itertools
library for complex iterators. - Async Comprehensions: Introduced in Python 3.6, they enable asynchronous iteration.
With practice, comprehensions will become a natural and powerful part of your Python toolkit. Happy coding!
Learn Python with Treehouse
Learning with Treehouse starts at only $25 per month. If you think you’re ready to start exploring if tech is right for you, sign up for your free seven day trial.
Hang out with us on Discord to learn our favorite tips, to network with like-minded peers, and to share how your learning is going. We’ll see you there!
If you liked reading this article, have a look at this one:
Thanks a lot for this! Really helped me out a lot!
Fantastic summary. Way better than the python documentation. 10 thumbs up!
Great article! 🙂
this was really helpful
Hi, anyone have an idea how to make this faster?
[f(x,y) for x in range(1000) for y in range(x, len(range(1000)))]?
Many thanks
Sometimes it is convenient to use single line for loops as follows:
for act in actions: act.activate()
Nicely structured introduction. Thank you.
BTW first worked example:
my_doubled_list = list_doubler(lst) s/b my_doubled_list = list_doubler(my_list)
Nice one Ken. This will get shared via the various Python FB groups.
This may be a stupid question, but what editor – color scheme combo is the main screenshot using?
It’s actually emacs running in my Mac terminal. Color scheme is flatui.