Python Comprehensions: List, Tuple, Dictionary, and Set
This article explains Python's comprehension syntax for lists, tuples, dictionaries, and sets, detailing their structures, execution order, and practical examples—including filtering, nested loops, and conditional logic—while showing how to convert generator objects and highlighting common use cases.
Comprehensions (also called generator expressions) are a Python-specific feature that allows rapid creation of lists, tuples, dictionaries, and sets from existing iterables.
Python List Comprehension
The syntax is [expression for item in iterable [if condition]] . The optional if clause can be omitted. It follows the same execution order as a traditional for loop, with the expression acting as the loop body.
<code>a_range = range(10)
# Apply for‑expression to a_range
a_list = [x * x for x in a_range]
# a_list contains 10 elements
print(a_list)</code>Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Adding an if clause filters elements, e.g., only even numbers:
<code>b_list = [x * x for x in a_range if x % 2 == 0]
# b_list contains 5 elements
print(b_list)</code>Output: [0, 4, 16, 36, 64]
Multiple for clauses enable nested loops:
<code>d_list = [(x, y) for x in range(5) for y in range(4)]
# d_list contains 20 elements
print(d_list)</code>Output: [(0, 0), (0, 1), …, (4, 3)]
A three‑level nested example:
<code>e_list = [[x, y, z] for x in range(5) for y in range(4) for z in range(6)]
# e_list contains 120 elements
print(e_list)</code>Using comprehensions for conditional pairing based on divisibility:
<code>src_a = [30, 12, 66, 34, 39, 78, 36, 57, 121]
src_b = [3, 5, 7, 11]
# Pair when y is divisible by x
result = [(x, y) for x in src_b for y in src_a if y % x == 0]
print(result)</code>Output: [(3, 30), (3, 12), …, (11, 121)]
Python Tuple Comprehension
The syntax uses parentheses: (expression for item in iterable [if condition]) . It produces a generator object, not a tuple.
<code>a = (x for x in range(1,10))
print(a) # <generator object ...>
print(tuple(a)) # (1, 2, 3, 4, 5, 6, 7, 8, 9)</code>To obtain elements you can:
Wrap with tuple() to convert the generator to a tuple.
Iterate with a for loop.
Use the __next__() method (note that the generator is exhausted after iteration).
Python Dictionary Comprehension
Syntax: {key: value for item in iterable [if condition]} . It uses curly braces.
<code>listdemo = ['C语言中文网', 'c.biancheng.net']
# Create a dict where each string is a key and its length is the value
newdict = {key: len(key) for key in listdemo}
print(newdict)</code>Output: {'C语言中文网': 6, 'c.biancheng.net': 15}
<code>olddict = {'C语言中文网': 6, 'c.biancheng.net': 15}
# Swap keys and values
newdict = {v: k for k, v in olddict.items()}
print(newdict)</code>Output: {6: 'C语言中文网', 15: 'c.biancheng.net'}
<code>olddict = {'C语言中文网': 6, 'c.biancheng.net': 15}
# Filter pairs where the value is greater than 10
newdict = {v: k for k, v in olddict.items() if v > 10}
print(newdict)</code>Output: {15: 'c.biancheng.net'}
Python Set Comprehension
Syntax mirrors dictionary comprehension but without key‑value pairs: {expression for item in iterable [if condition]} . The result is a set with unique elements.
<code>setnew = {i**2 for i in range(3)}
print(setnew)</code>Output: {0, 1, 4}
<code>tupledemo = (1,1,2,3,4,5,6,6)
setnew = {x**2 for x in tupledemo if x % 2 == 0}
print(setnew)</code>Output: {16, 4, 36}
<code>dictdemo = {'1':1, '2':2, '3':3}
setnew = {x for x in dictdemo.keys()}
print(setnew)</code>Output: {'1', '2', '3'}
These examples demonstrate how Python comprehensions provide concise, readable ways to construct and transform collections.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.