codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

36 / 68 topics
36List Comprehensions37Python Iterators38Python Generators39Python Decorators40Python Modules, Packages & PIP41Python Main Function (__name__ == '__main__')42Python Dates and Time43Python Regular Expressions44Python JSON
Tutorials/Python Programming/List Comprehensions
🐍Python Programming

List Comprehensions

Updated 2026-05-15
30 min read

List Comprehensions

List comprehensions are a concise way to create lists in Python. They provide a more readable alternative to using loops and conditionals for list creation. In this tutorial, we will explore advanced features of list comprehensions, including those with conditions, nested comprehensions, dictionary and set comprehensions, and generator expressions.

Introduction

List comprehensions are a powerful feature in Python that allow you to create lists in a more concise and readable manner. They consist of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put all kinds of objects in lists.

List comprehensions are not only syntactically cleaner but also often faster than using traditional loops to build lists. They are particularly useful when working with data transformation and filtering tasks.

List Comprehensions with Conditions

You can add conditions to list comprehensions by including an if clause. This allows you to filter the elements that are included in the resulting list based on a condition.

Example 1: Filtering Even Numbers

Python
1# script.py
2numbers = [1, 2, 3, 4, 5, 6]
3even_numbers = [num for num in numbers if num % 2 == 0]
4print(even_numbers)
Output

In this example, the list comprehension filters out non-positive temperatures from the temperatures list.

Nested Comprehensions

List comprehensions can also be nested to create more complex structures. This is useful when you need to iterate over multiple lists or perform multi-level transformations.

Example 3: Flattening a List of Lists

Python
1# script.py
2matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3flattened_list = [num for row in matrix for num in row]
4print(flattened_list)
Output

In this example, the nested list comprehension generates all possible combinations of colors and sizes.

Dictionary Comprehensions

Dictionary comprehensions allow you to create dictionaries in a similar concise manner as list comprehensions. They consist of key-value pairs within curly braces.

Example 5: Creating a Dictionary from a List

Python
1# script.py
2numbers = [1, 2, 3, 4, 5]
3squared_dict = {num: num ** 2 for num in numbers}
4print(squared_dict)
Output

In this example, the dictionary comprehension filters out students who did not pass based on a minimum score of 80.

Set Comprehensions

Set comprehensions are similar to list and dictionary comprehensions but create sets instead. They use curly braces like dictionaries but do not have key-value pairs.

Example 7: Creating a Set from a List

Python
1# script.py
2numbers = [1, 2, 3, 4, 5, 1, 2, 3]
3unique_numbers = {num for num in numbers}
4print(unique_numbers)
Output

In this example, the set comprehension filters out words that are shorter than or equal to five characters.

Generator Expressions

Generator expressions are similar to list comprehensions but use parentheses instead of square brackets. They generate items on-the-fly and do not store them in memory all at once, making them more memory-efficient for large datasets.

Example 9: Generating Even Numbers

Python
1# script.py
2even_numbers = (num for num in range(10) if num % 2 == 0)
3for number in even_numbers:
4 print(number)
Output
0
2
4
6
8

In this example, the generator expression generates even numbers from 0 to 9. The for loop iterates over the generator and prints each number.

Example 10: Summing Squares

Python
1# script.py
2squares_sum = sum(num ** 2 for num in range(5))
3print(squares_sum)
Output

In this example:

  • We define a list of dictionaries where each dictionary represents a book with a title and a publication year.
  • The get_recent_books function uses a list comprehension to filter books published after the specified year.
  • Finally, we call this function with the list of books and a year (2017) and print the titles of the recent books.

Summary

ConceptDescription
List ComprehensionsConcise way to create lists using expressions and optional conditions.
ConditionsFilter elements based on a condition using if clauses.
Nested ComprehensionsCreate complex structures by nesting multiple comprehensions.
Dictionary ComprehensionsCreate dictionaries in a concise manner with key-value pairs.
Set ComprehensionsCreate sets by removing duplicates and optionally filtering elements.
Generator ExpressionsGenerate items on-the-fly, more memory-efficient for large datasets.

What's Next?

Now that you have mastered list comprehensions, the next step is to learn about Python iterators. Iterators are a fundamental concept in Python that allow you to traverse through data structures like lists and dictionaries. Understanding iterators will help you write more efficient and flexible code.

Continue your journey by exploring Python Iterators to enhance your programming skills further.


PreviousPython EncapsulationNext Python Iterators

Recommended Gear

Python EncapsulationPython Iterators