CodingNic

Intermediate Python

Advanced Comprehensions

Intermediate Python 34 min read

Advanced Comprehensions

Advanced Comprehensions

You already learned basic comprehensions.

Example:

python
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]

Comprehensions can do more than simple lists.

You can add conditions, nested loops, sets, and dictionaries.

Why Comprehensions Matter

They help you:

  • write shorter code
  • transform data quickly
  • filter values easily
  • build collections cleanly

Review: Basic List Comprehension

python
numbers = [1, 2, 3, 4]

squares = [n * n for n in numbers]

print(squares)

Output

text
[1, 4, 9, 16]

Add Condition

python
numbers = [1, 2, 3, 4, 5, 6]

evens = [n for n in numbers if n % 2 == 0]

print(evens)

Output

text
[2, 4, 6]

If Else in Expression

python
numbers = [1, 2, 3, 4]

labels = ["Even" if n % 2 == 0 else "Odd" for n in numbers]

print(labels)

Output

text
['Odd', 'Even', 'Odd', 'Even']

Nested Loop Comprehension

python
pairs = [(x, y) for x in [1, 2] for y in ["A", "B"]]

print(pairs)

Output

text
[(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

Set Comprehension

python
numbers = [1, 1, 2, 2, 3]

unique = {n for n in numbers}

print(unique)

Output

text
{1, 2, 3}

Dictionary Comprehension

python
numbers = [1, 2, 3]

result = {n: n * n for n in numbers}

print(result)

Output

text
{1: 1, 2: 4, 3: 9}

Practical Example

python
names = ["tom", "maya", "liam"]

upper_names = [name.upper() for name in names]

print(upper_names)

Output

text
['TOM', 'MAYA', 'LIAM']

Code Along

Create a list of numbers 1 to 10.

Use a comprehension to create only odd numbers.

Mini Challenge

Use:

python
words = ["apple", "banana", "kiwi"]

Tasks:

  1. Create a list of word lengths

  2. Create a dictionary where:

    • key = word
    • value = length

Expected output:

text
[5, 6, 4]
{'apple': 5, 'banana': 6, 'kiwi': 4}

Real World Use Case

Developers use comprehensions for data cleaning, filtering, APIs, reports, and transformations.

Quiz

  1. Can comprehensions use conditions?
  2. What does a set comprehension create?
  3. What does a dictionary comprehension create?
  4. Why are comprehensions useful?

Assignment

Create a dictionary comprehension that maps numbers 1 to 5 to their cubes.

Summary

You learned how to use advanced comprehensions with conditions, nested loops, sets, and dictionaries.