Site icon Treehouse Blog

Python One Line for Loops [Tutorial]

Direct comparison between for loops and list comprehensions.

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:

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

Practice Makes Perfect

Here are a few exercises to try:

  1. Write a list comprehension that extracts all even numbers from a list.
  2. Use a dictionary comprehension to create a mapping of numbers to their cubes.
  3. Create a set comprehension that removes duplicates from a list of words.
  4. Challenge: Using a comprehension, create a list of tuples, where each tuple contains an element from two different lists.
  5. 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:

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:

Exit mobile version