Python Foundation

List Comprehensions

01 · What is List Comprehension? File · List Comprehensions · 1 of 13

What is List Comprehension?

List comprehension is a short and clean way to create a new list from an existing collection.

Normally, we create a list using:

  1. An empty list
  2. A loop
  3. A condition or calculation
  4. append()

List comprehension combines these steps into one readable line.

02 · Traditional vs Comprehension File · List Comprehensions · 2 of 13

Traditional Loop vs List Comprehension

Python
kids = ["Jaswitha", "dhanvik", "Divisha", "Kavya", "Rohansh"]

# Traditional way
chocolates = []
for kid in kids:
    chocolates.append(kid + " Gets a chocolate")
print(chocolates)
Python
# List Comprehension
chocolates = [kid + " Gets a chocolate" for kid in kids]
print(chocolates)
Both programs give the same result. The second one is shorter because list comprehension internally performs the looping and appending.
03 · Basic Syntax File · List Comprehensions · 3 of 13

Basic Syntax

new_list = [expression for item in collection]

  • collection → The existing list, tuple, string, range, set or other iterable
  • item → Each individual value taken from the collection
  • expression → What should be stored in the new list
Python
numbers = [1, 2, 3, 45]
squares = [number**2 for number in numbers]
print(squares)
04 · Using range() File · List Comprehensions · 4 of 13

List Comprehension with range()

You don't always need an existing list. You can use range().

Python
[number for number in range(1, 6)]

# squares from 1 to 10
[number**2 for number in range(1, 11)]

# cubes from 1 to 5
[number**3 for number in range(1, 6)]
05 · With Strings File · List Comprehensions · 5 of 13

List Comprehension with Strings

A string is also iterable. Python can process one character at a time.

Python
word = "PYTHON"
[character for character in word]

# convert every character to lowercase
[character.lower() for character in word]

names = ["kencha", "mohan", "manu", "Prashant"]
[name.upper() for name in names]
06 · With Condition (if) File · List Comprehensions · 6 of 13

List Comprehension with Condition

Sometimes we do not want to process every value. We only want values that satisfy a condition.

[expression for item in collection if condition]

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

# select even numbers
[number for number in numbers if number % 2 == 0]

# select odd numbers
[number for number in numbers if number % 2 != 0]

marks = [34, 67, 89, 45, 76, 23]
[mark for mark in marks if mark > 50]
07 · With if-else File · List Comprehensions · 7 of 13

List Comprehension with if-else

There is an important difference:

  • if → used for filtering
  • if-else → used for transforming every value

[value_if_true if condition else value_if_false for item in collection]

Python
numbers = [1, 2, 3, 4, 5]
["even" if number % 2 == 0 else "Odd" for number in numbers]

marks = [78, 24, 56, 31, 90]
["pass" if mark >= 35 else "fail" for mark in marks]
08 · Multiple Conditions File · List Comprehensions · 8 of 13

Multiple Conditions

Python
numbers = range(1, 31)

# divisible by both 2 and 3
[number for number in numbers if number % 2 == 0 and number % 3 == 0]

# divisible by 2 or 3
[number for number in numbers if number % 2 == 0 or number % 3 == 0]

marks = [34, 55, 67, 82, 76, 91, 49]
[mark for mark in marks if 50 <= mark <= 80]
09 · Working with Data File · List Comprehensions · 9 of 13

Practical Data Examples

Python
names = ["Arjun", "Ravi", "Anjali", "Meena", "Amit"]

# names starting with A
[name for name in names if name.startswith("A")]

# names longer than 4 characters
[name for name in names if len(name) > 4]

# cleaning text data
names = [" Ravi", "Sita  ", " John  "]
[name.strip() for name in names]

# convert string numbers to integers
numbers_as_text = ["10", "20", "30", "40"]
[int(value) for value in numbers_as_text]
10 · Nested Comprehensions File · List Comprehensions · 10 of 13

Nested List Comprehensions

A nested list comprehension contains more than one for.

Python
# Traditional nested loops
results = []
for row in range(1, 4):
    for column in range(1, 4):
        results.append((row, column))

# Nested List Comprehension
[(row, column) for row in range(1, 4) for column in range(1, 4)]

colors = ["Red", "Blue", "Black"]
sizes = ["M", "L"]
[(color, size) for color in colors for size in sizes]

# Flatten a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[number for row in matrix for number in row]
11 · Calling Functions File · List Comprehensions · 11 of 13

Calling Functions inside List Comprehension

Python
def calculate_square(number):
    return number**2

numbers = [1, 2, 3, 4, 5]
[calculate_square(number) for number in numbers]
Python
def calculate_grade(mark):
    if mark >= 75:
        return "Distinction"
    elif mark >= 60:
        return "First class"
    elif mark >= 35:
        return "Pass"
    else:
        return "Fail"

marks = [82, 65, 42, 23]
grade = [calculate_grade(mark) for mark in marks]
print(grade)
12 · enumerate() & zip() File · List Comprehensions · 12 of 13

List Comprehension with enumerate() and zip()

Python
students = ["Mohan", "Manohar", "Manu"]

numbered_students = [
    f"{index}.{name}"
    for index, name in enumerate(students, start=1)
]
print(numbered_students)
Python
names = ["ravi", "sita", "john"]
marks = [78, 92, 65]

result = [
    f"{name} scored {mark}"
    for name, mark in zip(names, marks)
]
print(result)
13 · Advantages & Summary File · List Comprehensions · 13 of 13

Advantages of List Comprehension

  1. Shorter code
  2. Easier to read
  3. Avoids repeated append()
  4. Faster for simple operations
  5. Useful for data cleaning:
    • Converting data types
    • Cleaning strings
    • Filtering records
    • Applying calculations
    • Creating labels

Disadvantage

Difficult to read when too complex.

Home List Comprehensions

List Comprehensions

Master the short and clean way to create lists in Python.

Select any topic from the left sidebar to begin.


Start Learning →