Python List Comprehensions

Python List Comprehensions Explained: From Beginner to Advanced with 10 Practical Examples for Data Processing

Learn Python list comprehensions step by step with 10 practical examples including filtering, nested loops, dictionary comprehensions, and performance comparisons against traditional loops.

List comprehensions are one of Python's most beloved features. They let you create new lists by applying an expression to each item in an iterable, all in a single line. Let's explore how to use them effectively.

Basic Syntax

new_list = [expression for item in iterable if condition]

1. Simple Transformation

Convert a list of strings to uppercase:

fruits = ['apple', 'banana', 'cherry']
upper_fruits = [f.upper() for f in fruits]
print(upper_fruits)  # ['APPLE', 'BANANA', 'CHERRY']

2. Filtering with Condition

Get only even numbers from a range:

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

3. Nested Loops (Flattening)

Flatten a matrix:

matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6]

4. Using if-else in Expression

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

5. Dictionary and Set Comprehensions

Similar syntax works for dictionaries and sets:

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

# Set comprehension
unique_lengths = {len(word) for word in ['hello', 'world', 'python']}  # {5, 6}

List comprehensions are not just concise—they're often faster than manual loops. Start using them today!

Comments

Popular posts from this blog

How to Center a Div - The 3 Modern Ways (2026)

Call by Value vs Call by Reference in C Programming (With Simple Examples)

Build a Simple Calculator with HTML, CSS & JavaScript