{}const=>[]async()letfn</>var
DevelopmentPython

List Comprehensions in Python: A Beginner's Guide

Learn list comprehensions in Python — a powerful tool for elegant list creation. A detailed guide with practical examples, from basic syntax to advanced techniques. Learn how to write clean and efficient Python code.

К

Kodik

Author

5 min read

What are list comprehensions?

List comprehension is a compact way to create a new list based on an existing sequence or iterable object. Instead of writing several lines with loops, you can express the same logic in one line.

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

Basic syntax

The basic structure of list comprehension looks like this:

новый_список = [выражение for элемент in последовательность]

Example: traditional approach vs list comprehension

Let's create a list of squares of numbers from 0 to 9.

Traditional approach:

squares = []
for i in range(10):
    squares.append(i ** 2)
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

With list comprehension:

squares = [i ** 2 for i in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The result is the same, but the second option is shorter and reads almost like a regular sentence: "create a list of squares i for each i in the range from 0 to 9".

Adding conditions

You can filter items by adding a condition at the end:

новый_список = [выражение for элемент in последовательность if условие]

Examples with conditions

Only even numbers:

evens = [i for i in range(20) if i % 2 == 0]
print(evens)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Squares of odd numbers only:

odd_squares = [i ** 2 for i in range(10) if i % 2 != 0]
print(odd_squares)
# [1, 9, 25, 49, 81]

Row filtering:

words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = [word for word in words if len(word) > 5]
print(long_words)
# ['banana', 'cherry', 'elderberry']

Working with strings

List comprehensions are great for processing strings.

Conversion to upper case:

names = ["anna", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)
# ['ANNA', 'BOB', 'CHARLIE']

Extracting the first letters:

words = ["Python", "is", "awesome"]
first_letters = [word[0] for word in words]
print(first_letters)
# ['P', 'i', 'a']

Nested loops

List comprehensions support nested loops for working with multidimensional data.

Creating coordinate pairs:

coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Multiplication of elements of two lists:

list1 = [1, 2, 3]
list2 = [10, 20, 30]
products = [x * y for x in list1 for y in list2]
print(products)
# [10, 20, 30, 20, 40, 60, 30, 60, 90]

Conditional if-else operator

You can use the ternary operator for more complex logic:

новый_список = [выражение_if if условие else выражение_else for элемент in последовательность]

Example: replace even with "even", leave odd as it is:

numbers = [1, 2, 3, 4, 5, 6]
result = ["even" if n % 2 == 0 else n for n in numbers]
print(result)
# [1, 'even', 3, 'even', 5, 'even']

Practical examples

Working with dictionaries

Extracting values:

prices = {"apple": 50, "banana": 30, "cherry": 80}
expensive = [fruit for fruit, price in prices.items() if price > 40]
print(expensive)
# ['apple', 'cherry']

Processing files

Reading and filtering rows:

# Let's say we have a file with text
lines = ["  hello  ", "world", "  Python  ", ""]
cleaned = [line.strip() for line in lines if line.strip()]
print(cleaned)
# ['hello', 'world', 'Python']

Mathematical operations

Applying the function to all elements:

import math
numbers = [4, 9, 16, 25]
roots = [math.sqrt(n) for n in numbers]
print(roots)
# [2.0, 3.0, 4.0, 5.0]

When NOT to use list comprehensions

Despite the elegance, there are situations when traditional cycles are preferable:

  1. Complex logic: if the expression becomes too long and difficult to read

  2. Side effects: list comprehensions are designed to create lists, not to perform actions

  3. Deep nesting: more than two nested loops make the code unreadable

Bad example (too complicated):

# Don't do that!
result = [x * y if x % 2 == 0 else x + y for x in range(10) if x > 5 for y in range(10) if y % 3 == 0]

It is better to split into several lines with regular loops.

Other types of comprehensions

Python supports not only list comprehensions:

Dictionary comprehension:

squares_dict = {x: x ** 2 for x in range(5)}
print(squares_dict)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set comprehension:

unique_squares = {x ** 2 for x in [1, 2, 2, 3, 3, 4]}
print(unique_squares)
# {1, 4, 9, 16}

Generator expression (to save memory):

squares_gen = (x ** 2 for x in range(1000000))
# Creates a generator, not a list, saving memory

Performance

List comprehensions usually work faster than equivalent loops with append() because they are optimized at the Python interpreter level.

Conclusion

List comprehensions are a powerful tool that makes your Python code more elegant and readable. Start with simple examples, practice on real tasks, and over time you will use them naturally and effectively.

Key points to remember:

  • List comprehensions make the code shorter and more expressive

  • You can add conditions for filtering

  • Nested loops are supported

  • Do not abuse complexity - readability is more important than brevity

  • There are also dict, set comprehensions and generator expressions

Practice, experiment, and list comprehensions will become a natural part of your Python programming style!

Join Code - our developer training app! We have friendly community in the Telegram channel, where beginners and experienced programmers share knowledge, help each other with tasks and discuss new technologies. Learn with us!

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card