Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Comprehensions

Learn how to create Lists, Sets and Dictionaries in a concise and readable way using Python Comprehensions.

What are Comprehensions?

Comprehensions provide a short and expressive way to create new collections from existing iterables.

Instead of writing multiple lines using a loop and append(), a comprehension can often perform the same task in a single readable expression.

Python commonly provides:

  • List Comprehension
  • Set Comprehension
  • Dictionary Comprehension

Comprehensions are especially useful when transforming, filtering or creating collections of data.

Normal Loop vs Comprehension

Using a Normal Loop

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

squares = []

for number in numbers:
    squares.append(number * number)

print(squares)

Output:

[1, 4, 9, 16, 25]

Using List Comprehension

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

squares = [number * number for number in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

Both approaches produce the same result, but the comprehension is more compact.

1. List Comprehension

List Comprehension is used to create a new List from an existing iterable.

Basic Syntax

[expression for item in iterable]

Example

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

squares = [number * number for number in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

Using range() with List Comprehension

squares = [
    number * number
    for number in range(1, 6)
]

print(squares)

Output:

[1, 4, 9, 16, 25]

List Comprehension with Strings

A string is iterable, so we can process its characters using List Comprehension.

name = "Python"

letters = [character.upper() for character in name]

print(letters)

Output:

['P', 'Y', 'T', 'H', 'O', 'N']

List Comprehension with Condition

A condition can be used to filter values.

Syntax

[expression for item in iterable if condition]

Example

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

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print(even_numbers)

Output:

[2, 4, 6]

Filtering Odd Numbers

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

odd_numbers = [
    number
    for number in numbers
    if number % 2 != 0
]

print(odd_numbers)

Output:

[1, 3, 5]

if-else in List Comprehension

An if-else expression can be used to transform each item based on a condition.

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

result = [
    "Even" if number % 2 == 0 else "Odd"
    for number in numbers
]

print(result)

Output:

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

Notice that the if-else expression appears before the for part.

Multiple Conditions

Multiple filtering conditions can be combined using logical operators.

numbers = range(1, 11)

result = [
    number
    for number in numbers
    if number > 3 and number < 8
]

print(result)

Output:

[4, 5, 6, 7]

Nested List Comprehension

A List Comprehension can contain more than one for clause.

matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
]

result = [
    number
    for row in matrix
    for number in row
]

print(result)

Output:

[1, 2, 3, 4, 5, 6]

Nested comprehensions are powerful, but they should remain readable.

2. Set Comprehension

Set Comprehension creates a Set using a concise expression.

Syntax

{expression for item in iterable}

Example

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

squares = {
    number * number
    for number in numbers
}

print(squares)

Duplicate results are automatically removed because the result is a Set.

Set Comprehension with Condition

numbers = range(1, 11)

even_squares = {
    number * number
    for number in numbers
    if number % 2 == 0
}

print(even_squares)

This creates a Set containing squares of even numbers.

3. Dictionary Comprehension

Dictionary Comprehension creates a new Dictionary using a concise expression.

Syntax

{key: value for item in iterable}

Example

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

squares = {
    number: number * number
    for number in numbers
}

print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dictionary Comprehension with Condition

numbers = range(1, 11)

even_squares = {
    number: number * number
    for number in numbers
    if number % 2 == 0
}

print(even_squares)

Output:

{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Transforming Dictionary Values

marks = {
    "Rahul": 80,
    "Sneha": 90,
    "Amit": 75
}

updated_marks = {
    name: mark + 5
    for name, mark in marks.items()
}

print(updated_marks)

Output:

{'Rahul': 85, 'Sneha': 95, 'Amit': 80}

Filtering a Dictionary

marks = {
    "Rahul": 80,
    "Sneha": 45,
    "Amit": 75,
    "Priya": 35
}

passed_students = {
    name: mark
    for name, mark in marks.items()
    if mark >= 50
}

print(passed_students)

Output:

{'Rahul': 80, 'Amit': 75}

CIIT Example - Course Names 🤓📩

Suppose CIIT has a list of course names and wants to convert them into uppercase.

courses = [
    "python",
    "java",
    ".net",
    "mern"
]

updated_courses = [
    course.upper()
    for course in courses
]

print(updated_courses)

Output:

['PYTHON', 'JAVA', '.NET', 'MERN']

CIIT Example - Students 🤓📩

Suppose CIIT wants to select students who scored at least 60 marks.

students = {
    "Rahul": 85,
    "Sneha": 55,
    "Amit": 72,
    "Priya": 48
}

qualified_students = {
    name: marks
    for name, marks in students.items()
    if marks >= 60
}

print(qualified_students)

Output:

{'Rahul': 85, 'Amit': 72}

CIIT Example - Course Filter 🤓📩

We can filter a List and create a new List containing only Python-related courses.

courses = [
    "Python",
    "Java",
    "Python Full Stack",
    ".NET",
    "Data Science",
    "Python"
]

python_courses = [
    course
    for course in courses
    if "Python" in course
]

print(python_courses)

Output:

['Python', 'Python Full Stack', 'Python']

Types of Comprehensions

Type Syntax Result
List [expression for item in iterable] List
Set {expression for item in iterable} Set
Dictionary {key: value for item in iterable} Dictionary

When Should You Use Comprehensions?

  • When creating a collection from another iterable.
  • When applying a simple transformation.
  • When filtering values using a clear condition.
  • When the resulting expression remains easy to understand.

If a comprehension becomes too complicated, using a normal loop may make the code easier to read and maintain.

Common Mistakes

  1. Confusing List Comprehension syntax with Dictionary Comprehension syntax.
  2. Placing an if-else expression in the wrong position.
  3. Creating very complex nested comprehensions that are difficult to understand.
  4. Forgetting that Set Comprehension removes duplicate values.
  5. Using comprehensions when a normal loop would make the code clearer.

Interview Points

  • What is List Comprehension?
  • What is the basic syntax of List Comprehension?
  • How do you add a condition to a comprehension?
  • What is Set Comprehension?
  • What is Dictionary Comprehension?
  • What is the difference between a normal loop and a List Comprehension?
  • Can you use multiple conditions in a comprehension?
  • When should you avoid using comprehensions?

CIIT Learning Point

Comprehensions provide a concise way to create and transform Python collections. List, Set and Dictionary Comprehensions are especially useful for filtering and transforming data. Always prefer readability over writing an unnecessarily complicated one-line expression.

CIIT Practice Tasks

  1. Create a List of squares from 1 to 10 using List Comprehension.
  2. Create a List containing only even numbers from 1 to 50.
  3. Convert a List of names into uppercase using List Comprehension.
  4. Create a Set containing unique squares of numbers.
  5. Create a Dictionary where numbers from 1 to 10 are keys and their squares are values.
  6. From a Dictionary of student marks, create a new Dictionary containing only students who passed.
  7. Create a List containing only CIIT courses whose name contains "Python".

Summary :

Python Comprehensions provide a concise and readable way to create collections from existing iterables. List Comprehension creates Lists, Set Comprehension creates Sets, and Dictionary Comprehension creates key-value collections. Conditions can be used for filtering and expressions can be used for transforming values. Comprehensions are powerful, but they should always be written with readability in mind.