Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

List and Dictionary Comprehensions

Recommended resources

Welcome to your first lesson! This course is designed to equip you with the essential Python tools and algorithmic techniques needed for competitive programming. We'll start by mastering some powerful, built-in Python features that allow you to write clean, efficient, and concise code—a significant advantage in timed programming contests.

In this lesson, we'll focus on a fundamental Pythonic feature: list and dictionary comprehensions. You'll learn how to use them to create and manipulate collections in a single, readable line of code, moving beyond the traditional for loops you're already familiar with. This will help you write faster, both in terms of execution speed and coding time.

1. From for Loops to List Comprehensions

You already know how to build a list using a for loop and the .append() method. For example, to create a list of the first 10 square numbers, you would write:

squares = []
for i in range(10):
    squares.append(i * i)
# squares is now [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This is clear, but it takes up three lines. A list comprehension achieves the same result in one line, with a structure that is often more readable once you get used to it.

The basic syntax is: [expression for member in iterable]

Let's see it in action for the same example:

squares = [i * i for i in range(10)]
# squares is now [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This reads like a sentence: "create a new list with i * i for each i in the range from 0 to 9."

To get a solid grasp of this fundamental syntax, watch the following short video segment. It does an excellent job of comparing the for loop approach with the list comprehension syntax.

Python Tutorial: Comprehensions - How they work and why you should be using them

Watch this segment from Corey Schafer's "Python Tutorial: Comprehensions" to see a side-by-side comparison of creating a list with a for loop versus a list comprehension.

Watch the beginning of the video from 00:00 to 02:33. Pay close attention to how the structure of the for loop is rearranged to form the comprehension.


2. Filtering and Transforming Elements

Comprehensions become even more powerful when you add logic. You can transform elements and filter them based on conditions.

Filtering with if

You can add an if statement at the end of a comprehension to include only the elements that satisfy a certain condition.

The syntax is: [expression for member in iterable if condition]

For example, let's create a list of even numbers from 0 to 49.

With a for loop:

evens = []
for number in range(50):
    if number % 2 == 0:
        evens.append(number)

With a list comprehension:

evens = [number for number in range(50) if number % 2 == 0]

The following video segment demonstrates this filtering capability and also shows how you can apply transformations (like squaring a number) to each element.

10 Python Comprehensions You SHOULD Be Using

This segment from Tech With Tim's video "10 Python Comprehensions You SHOULD Be Using" clearly explains how to add an if condition to filter elements in a list comprehension.

Watch from 02:05 to 04:25. Notice how the if clause is placed at the end of the comprehension to act as a filter.

You can even chain multiple if conditions. For example, to find numbers divisible by both 2 and 3 in a range:
[x for x in range(30) if x % 2 == 0 if x % 3 == 0]

Test your understanding!

Given a list of strings words = ["programming", "is", "fun", "and", "powerful"], use a list comprehension to create a new list containing only the words that have more than 5 characters, converted to uppercase.

Show answer
words = ["programming", "is", "fun", "and", "powerful"]
long_words_upper = [word.upper() for word in words if len(word) > 5]
# Result: ['PROGRAMMING', 'POWERFUL']

Conditional Transformation with if-else

What if you want to apply a different transformation based on a condition, rather than just filtering? For this, you use a conditional expression (sometimes called a ternary operator) at the beginning of the comprehension.

The syntax is: [expression_if_true if condition else expression_if_false for member in iterable]

Notice the different placement of the if-else block compared to the filtering if.

Let's create a list that labels numbers from 0 to 9 as 'even' or 'odd'.

labels = ['even' if x % 2 == 0 else 'odd' for x in range(10)]
# Result: ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

This video explains this powerful pattern.

10 Python Comprehensions You SHOULD Be Using

This next segment from the Tech With Tim video demonstrates how to use an if-else statement to choose what value to place in the list for each element.

Watch from 09:21 to 11:24. Focus on the key difference: the if-else structure goes before the for loop and is used for transformation, not filtering.


3. Nested List Comprehensions

For more complex data structures, like a list of lists (a matrix), you can use nested for loops within a comprehension. A common use case is to "flatten" a matrix into a single list.

Consider this matrix: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The for loop approach to flatten it would be:

flattened = []
for row in matrix:
    for num in row:
        flattened.append(num)

With a nested list comprehension, the loops appear in the same order:

flattened = [num for row in matrix for num in row]
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The rule is simple: the for loops are written from left to right in the same order as you would nest them.

Test your understanding!

You have a list of teams, and each team is a list of player names: teams = [["Alice", "Bob"], ["Charlie", "David"]]. Use a nested list comprehension to create a single list of all player names.

Show answer
teams = [["Alice", "Bob"], ["Charlie", "David"]]
all_players = [player for team in teams for player in team]
# Result: ['Alice', 'Bob', 'Charlie', 'David']

4. Dictionary Comprehensions

The same concept of comprehensions can be applied to create dictionaries. This is extremely useful for building dictionaries on the fly, for instance, from two lists or by transforming an existing iterable.

The syntax is: {key_expression: value_expression for member in iterable}

For example, let's create a dictionary mapping numbers to their squares:

square_dict = {x: x*x for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

You can also include an if condition for filtering, just like with list comprehensions.

A very common pattern in competitive programming is to create a mapping from two lists. The zip() function is perfect for this.

names = ['Bruce', 'Clark', 'Peter']
heroes = ['Batman', 'Superman', 'Spiderman']

hero_dict = {name: hero for name, hero in zip(names, heroes)}
# Result: {'Bruce': 'Batman', 'Clark': 'Superman', 'Peter': 'Spiderman'}

The following image provides a helpful visual metaphor for how dictionary comprehensions work.

Visualizing Python Dictionary Comprehensions
This diagram illustrates the "factory" process of a dictionary comprehension: creating key-value pairs from an iterable, transforming them, and applying optional filters.

For a detailed explanation with more examples, please read the following article from GeeksForGeeks.

Python Dictionary Comprehension

This article, "Python Dictionary Comprehension," provides a concise overview of the syntax and common use cases for creating dictionaries efficiently.

Read the introduction, the 'Syntax' and 'Creating a Dictionary from Two Lists' sections, and the 'Dictionary Comprehension with Conditional Statements' section. Focus on how the key-value pair is defined and how zip() and if conditions are used.


Why Bother with Comprehensions?

You might wonder why we need comprehensions when for loops work just fine. In competitive programming, the reasons are compelling:

  1. Conciseness and Readability: Comprehensions pack the logic of creating a collection into a single, expressive line. This makes your code cleaner and faster to write and read, once you're familiar with the syntax.
  2. Performance: Comprehensions are often faster than the equivalent for loop that uses .append(). This is because the operations are optimized in Python's C implementation. In a timed contest, even small performance gains can matter.

To explore this topic further, the following article provides a great summary.

When to Use a List Comprehension in Python

The article "When to Use a List Comprehension in Python" from Real Python provides a great overview of the benefits of comprehensions and their syntax.

Read the sections 'Transforming Lists in Python' and 'Filter Values From a List'. This will reinforce the syntax for basic, filtering, and conditional comprehensions.


Conclusion

In this lesson, we've unlocked a powerful feature of Python that is indispensable for competitive programming. You now have the tools to write more compact and efficient code for creating and transforming lists and dictionaries.

Here are the key takeaways:

  • List Comprehensions provide a concise syntax [expression for member in iterable] to replace multi-line for loops.
  • You can filter elements by adding if condition at the end.
  • You can perform conditional transformation using ... if condition else ... at the beginning.
  • Nested comprehensions allow you to work with nested data structures like matrices.
  • Dictionary Comprehensions {key: value for ...} extend this power to creating dictionaries, often used with zip() to combine iterables.

Mastering comprehensions is a big step toward writing effective "Pythonic" code. Practice using them whenever you need to build a new list or dictionary from an existing one.

Up Next: In the next lesson, we will explore lambda functions. These are small, anonymous functions that you can define inline. You'll see how they are particularly useful when combined with other functions, such as sorting, and how they can further enhance the conciseness of your code.