List, Set, and Dictionary Comprehensions

📘 Python 👁 48 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

List, Set, and Dictionary Comprehensions in Python

Python provides comprehensions as a concise way to create lists, sets, and dictionaries in a single line. They make code more readable and efficient.


1. List Comprehensions

  • Create a list by applying an expression to each item in an iterable.

  • Optional condition to filter items.

Syntax:

[expression for item in iterable if condition]

Examples:

# Square of numbers numbers = [1, 2, 3, 4, 5] squares = [x**2 for x in numbers] print(squares) # [1, 4, 9, 16, 25] # Even numbers only even_numbers = [x for x in numbers if x % 2 == 0] print(even_numbers) # [2, 4] # Nested loops pairs = [(x, y) for x in [1, 2] for y in [3, 4]] print(pairs) # [(1, 3), (1, 4), (2, 3), (2, 4)]

2. Set Comprehensions

  • Similar to list comprehensions but create sets.

  • Removes duplicates automatically.

Syntax:

{expression for item in iterable if condition}

Examples:

numbers = [1, 2, 2, 3, 4, 4, 5] squared_set = {x**2 for x in numbers} print(squared_set) # {1, 4, 9, 16, 25} # Set of even numbers even_set = {x for x in numbers if x % 2 == 0} print(even_set) # {2, 4}

3. Dictionary Comprehensions

  • Create dictionaries using key-value pairs in a concise format.

Syntax:

{key_expression: value_expression for item in iterable if condition}

Examples:

# Numbers and their squares numbers = [1, 2, 3, 4, 5] squares_dict = {x: x**2 for x in numbers} print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Filter only even numbers even_dict = {x: x**2 for x in numbers if x % 2 == 0} print(even_dict) # {2: 4, 4: 16} # Swapping keys and values original = {'a': 1, 'b': 2} swapped = {v: k for k, v in original.items()} print(swapped) # {1: 'a', 2: 'b'}

4. Key Points

  • Comprehensions provide compact syntax for constructing sequences.

  • Can include conditions (if) and nested loops.

  • List comprehension → list

  • Set comprehension → set

  • Dictionary comprehension → dictionary

  • Improves readability and efficiency over traditional loops.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes