Fundamentals 9 min read

Python List Comprehensions: Syntax, Examples, and Advanced Uses

This article introduces Python list comprehensions, explaining their concise syntax, basic and advanced usage patterns such as filtering, nested loops, dictionary and set comprehensions, and demonstrates numerous practical examples with code snippets for tasks like generating squares, filtering even numbers, combining lists, and processing files.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python List Comprehensions: Syntax, Examples, and Advanced Uses

List comprehensions provide a concise way to create lists in Python by combining iteration, optional filtering, and expression evaluation in a single line.

Basic syntax : [expression for item in iterable if condition] , where expression is applied to each item , for defines the loop, and an optional if filters items.

Basic usage – generate squares of numbers 0‑9:

# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Filtering even numbers:

# Only square even numbers
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

String handling – convert each word to uppercase:

words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON']

Nested loops – generate Cartesian product of colors and sizes:

colors = ['red', 'green']
sizes = ['S', 'M', 'L']
combinations = [(color, size) for color in colors for size in sizes]
print(combinations)  # [('red', 'S'), ('red', 'M'), ('red', 'L'), ('green', 'S'), ('green', 'M'), ('green', 'L')]

Combining with zip() – element‑wise addition of two lists:

numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
summed = [x + y for x, y in zip(numbers1, numbers2)]
print(summed)  # [11, 22, 33]

Complex expression – compute Fibonacci numbers (first 10):

fibonacci = [0, 1] + [fibonacci[i-1] + fibonacci[i-2] for i in range(2, 10)]
print(fibonacci)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Dictionary comprehension – build a dict from two lists:

keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
person_info = {k: v for k, v in zip(keys, values)}
print(person_info)  # {'name': 'Alice', 'age': 25, 'city': 'New York'}

Set comprehension – remove duplicates from a list:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {n for n in numbers}
print(unique_numbers)  # {1, 2, 3, 4, 5}

Multiple conditions – filter numbers ≥10 and divisible by 3:

filtered_numbers = [x for x in range(20) if x >= 10 and x % 3 == 0]
print(filtered_numbers)  # [12, 15, 18]

Using enumerate() – get index and value:

fruits = ['apple', 'banana', 'cherry']
indexed_fruits = [(i, fruit) for i, fruit in enumerate(fruits)]
print(indexed_fruits)  # [(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Applying a function with list comprehension (instead of map() ):

words = ["hello", "world", "python"]
upper_words = [str.upper(word) for word in words]
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON']

Flatten a 2‑D list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in matrix for item in sublist]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Filter specific characters from a string:

text = "Hello, World! 123"
letters_only = [char for char in text if char.isalpha()]
print(''.join(letters_only))  # HelloWorld

Cartesian product of two lists:

list1 = ['a', 'b']
list2 = [1, 2]
cartesian_product = [(x, y) for x in list1 for y in list2]
print(cartesian_product)  # [('a', 1), ('a', 2), ('b', 1), ('b', 2)]

Conditional mapping using a dictionary:

data = [1, 2, 3, 4, 5]
category_map = {1: 'low', 2: 'low', 3: 'medium', 4: 'high', 5: 'high'}
categories = [category_map[x] for x in data]
print(categories)  # ['low', 'low', 'medium', 'high', 'high']

Count character occurrences in a string:

from collections import Counter
text = "abracadabra"
char_counts = {char: count for char, count in Counter(text).items()}
print(char_counts)  # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}

Generate a list of random integers:

import random
random_numbers = [random.randint(1, 100) for _ in range(10)]
print(random_numbers)

List comprehension with if‑else expression:

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

Process file lines – strip whitespace:

with open('example.txt', 'r') as file:
    lines = [line.strip() for line in file.readlines()]
print(lines)

Build a simple 3×3 matrix using nested comprehensions:

matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Data Processingtutorialexamplescodinglist comprehension
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.