Fundamentals 16 min read

Master Python List Comprehensions: When to Use Them and Why They Shine

This article explores Python's versatile list comprehension feature, comparing it with traditional loops and map() calls, demonstrating syntax, performance benchmarks, advanced usages like conditional logic, set and dictionary comprehensions, nested structures, and guidelines on when to prefer or avoid comprehensions for clear, efficient code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python List Comprehensions: When to Use Them and Why They Shine

Advantages of List Comprehensions

More time‑ and space‑efficient than loops.

Requires fewer lines of code.

Transforms iterative statements into a concise expression.

How to Create Lists in Python

List comprehensions are a syntax for building a new list from an existing iterable. Below are several ways to create a list.

Using a Loop

The classic way is to instantiate an empty list and append items inside a loop.

numbers = []
for number in range(10):
    numbers.append(number)
print(numbers)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using map()

map()

applies a function to each element of an iterable and returns a map object.

VAT_PERCENT = 0.1  # 10%

def add_vat(price):
    return price + (price * VAT_PERCENT)

prices = [10.03, 8.6, 32.85, 41.5, 22.64]
grand_prices = map(add_vat, prices)
print(list(grand_prices))
# Output: [11.03, 9.46, 36.14, 45.65, 24.9]

Using a List Comprehension

The Pythonic way rewrites the loop in a single line.

numbers = [number for number in range(10)]
print(numbers)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Which Method Is Most Efficient?

Benchmarking shows that map() is fastest, followed by list comprehensions, then loops.

import random, timeit

VAT_PERCENT = 0.1
PRICES = [random.randrange(100) for x in range(100000)]

def add_vat(price):
    return price + (price * VAT_PERCENT)

def get_grand_prices_with_map():
    return list(map(add_vat, PRICES))

def get_grand_prices_with_comprehension():
    return [add_vat(price) for price in PRICES]

def get_grand_prices_with_loop():
    grand_prices = []
    for price in PRICES:
        grand_prices.append(add_vat(price))
    return grand_prices

print(timeit.timeit(get_grand_prices_with_map, number=100))
print(timeit.timeit(get_grand_prices_with_comprehension, number=100))
print(timeit.timeit(get_grand_prices_with_loop, number=100))
# Sample output:
# 0.98 (map)
# 1.20 (comprehension)
# 1.36 (loop)

Choose the method based on readability and the specific goal of your code.

Use map() for high efficiency. Use loops for clearer step‑by‑step logic. Use list comprehensions for compact, readable code.

Advanced Comprehensions

Conditional Logic

You can add an if clause to filter items.

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

Complex conditions can be delegated to a helper function.

def is_prime(number):
    if number > 1:
        for el in range(2, int(number/2)+1):
            if number % el == 0:
                return False
        else:
            return True

numbers = [number for number in range(20) if is_prime(number)]
print(numbers)
# Output: [2, 3, 5, 7, 11, 13, 17, 19]

Conditional expressions can also transform values:

price_list = [1.34, 19.01, -4.2, 6, 8.78, -1, 1]
normalized_price_list = [price if price > 0 else -price for price in price_list]
print(normalized_price_list)
# Output: [1.34, 19.01, 4.2, 6, 8.78, 1, 1]

Set Comprehensions

Using curly braces creates a set without duplicate elements.

string = "Excellent"
unique_string = {letter for letter in string}
print(unique_string)
# Output: {'E', 'e', 'n', 't', 'x', 'c', 'l'}

Dictionary Comprehensions

Define a key‑value pair inside the braces.

string = "Words are but wind"
word_order = {el: ind+1 for ind, el in enumerate(string.split())}
print(word_order)
# Output: {'Words': 1, 'are': 2, 'but': 3, 'wind': 4}

The Walrus Operator

Introduced in Python 3.8, it assigns and returns a value in one expression.

import random

def get_weather_data():
    return random.randrange(90, 110)

hot_temps = [temp for _ in range(20) if (temp := get_weather_data()) >= 100]
print(hot_temps)
# Example output: [108, 100, 106, 103, 108, 106, 103, 104, 109, 106]

When Not to Use Comprehensions

Although concise, comprehensions can hurt readability or performance for very large data sets. In such cases, consider loops or generators.

Nested Comprehensions

They can build complex structures like matrices, but may become hard to read.

# Matrix creation with nested list comprehensions
matrix = [[x for x in range(7)] for y in range(6)]
print(matrix)
# Output: [[0,1,2,3,4,5,6], ... (6 rows)]

Flattening a matrix with a double‑for comprehension:

matrix = [[0,1,0],[1,0,1],[2,1,2]]
flat = [num for row in matrix for num in row]
print(flat)
# Output: [0, 1, 0, 1, 0, 1, 2, 1, 2]

For large data, generators use less memory:

summary = sum((x for x in range(1000000000)))
print(summary)
# Output: 499999999500000000

Performance comparison between map() and a generator shows the generator can be faster for this task.

import timeit

def get_sum_with_map():
    return sum(map(lambda x: x, range(1000000000)))

def get_sum_with_generator():
    return sum(x for x in range(1000000000))

print(timeit.timeit(get_sum_with_map, number=100))
print(timeit.timeit(get_sum_with_generator, number=100))
# Sample output: 4940.84 (map) vs 3464.20 (generator)

Conclusion

The article introduced Python list comprehensions, demonstrated how they can replace loops and map() calls, covered advanced features such as conditional logic, set and dictionary comprehensions, nested structures, and provided guidance on when to use or avoid them for clean, efficient code.

Learned several alternative ways to create lists.

Identified the advantages of each method.

Can simplify loops and map() calls with comprehensions.

Understood how to add conditional logic to comprehensions.

Can create set and dictionary comprehensions.

Learned when not to use comprehensions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonTutorialcodinglist-comprehension
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.