Fundamentals 14 min read

Understanding Python List Comprehensions: Advantages, Usage, and Performance Comparison

This article explains how Python list comprehensions provide a concise, memory‑efficient way to create lists, compares them with loops and map(), shows advanced features like conditional logic, nested comprehensions, set and dictionary comprehensions, and discusses when to avoid them for better readability and performance.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python List Comprehensions: Advantages, Usage, and Performance Comparison

Why Use List Comprehensions

Python offers several methods to build lists: traditional loops, the map() function, and list comprehensions. List comprehensions are faster and use less memory than loops, require fewer lines of code, and can turn iterative statements into clear expressions.

Creating Lists with a Loop

numbers = []
for number in range(10):
    numbers.append(number)
print(numbers)

The loop instantiates an empty list, iterates over range(10), and appends each number.

Using map()

VAT_PERCENT = 0.1

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

prices = [10.03, 8.6, 32.85, 41.5, 22.64]
grand_prices = list(map(add_vat, prices))
print(grand_prices)
map()

applies a function to each element of an iterable, returning a map object that can be converted to a list.

List Comprehension

numbers = [number for number in range(10)]
print(numbers)

This single‑line expression produces the same result as the loop but is more compact and readable.

Performance Comparison

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))

The timing results show that map() is the fastest, followed by list comprehensions, with the explicit loop being the slowest.

Advanced Comprehensions

Conditional logic can be added to filter items:

numbers = [number for number in range(20) if number % 2 == 0]
print(numbers)  # [0, 2, 4, ..., 18]

Complex conditions can be expressed with ternary operators:

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)

Set and dictionary comprehensions use curly braces to create unique collections or key‑value mappings:

# Set comprehension
string = "Excellent"
unique_string = {letter for letter in string}
print(unique_string)

# Dictionary comprehension
string = "Words are but wind"
word_order = {el: ind+1 for ind, el in enumerate(string.split())}
print(word_order)

When Not to Use Comprehensions

Nested comprehensions can become hard to read, especially for complex transformations like flattening matrices. In such cases, a regular for loop may be clearer.

# Flattening a matrix with a nested comprehension (concise but dense)
matrix = [[0,1,0],[1,0,1],[2,1,2]]
flat = [num for row in matrix for num in row]
print(flat)

# Same operation with explicit loops (more readable)
flat = []
for row in matrix:
    for num in row:
        flat.append(num)
print(flat)

Using Generators for Large Data Sets

List comprehensions store the entire list in memory, which can be problematic for huge data. Generators evaluate items lazily:

summary = sum((x for x in range(1_000_000_000)))
print(summary)

Performance tests show generators are more memory‑efficient and often faster than map() for massive sequences.

Conclusion

The article introduced list comprehensions, demonstrated their syntax, compared performance with loops and map(), covered conditional, set, and dictionary comprehensions, and advised when to prefer simpler loops for readability.

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.

performancePythongeneratordictionary comprehensionset-comprehensionConditional Logic
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

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.