Python has list comprehension and dictionary comprehension as a concise way to create a list or a dictionary by modifying an existing iterable.
Python also has generator expressions that allow you to create an iterable by modifying and potentially filtering each element in another iterable and passing the result in a function, for instance.
Does Python have a tuple comprehension statement? And why or why not? And what to use instead if not?
This tutorial will answer all your questions but first, let’s repeat the three related concepts:
- list comprehension,
- dictionary comprehension,
- generator expression
If you already know these concepts well, go ahead and skip right to the end of the tutorial! 🧑💻
List Comprehension
List comprehension is a compact way of creating lists. The simple formula is [expression + context]
.
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
for
andif
statements.
The example [x+100 for x in range(3)]
creates the list [100, 101, 102]
.
lst = [x for x in range(3)] print(lst) # [100, 101, 102]
💡 Learn More: List Comprehension in Python — A Helpful Illustrated Guide
Dictionary Comprehension
Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code.
It consists of two parts: expression and context.
- The expression defines how to map keys to values.
- The context loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.
The following example shows how to use dictionary comprehension to create a mapping from women to man:
men = ['Bob', 'Frank', 'Pete'] women = ['Alice', 'Ann', 'Liz'] # One-Liner Dictionary Comprehension pairs = {w:m for w, m in zip(women, men)} # Print the result to the shell print(pairs) # {'Bob': 'Alice', 'Frank': 'Ann', 'Pete': 'Liz'}
Also, watch the following video for a quick recap on dictionary comprehension:
💡 Learn More: Python Dictionary Comprehension: A Powerful One-Liner Tutorial
Set Comprehension
Set comprehension is a concise way of creating sets in Python using the curly braces notation {expression for element in context}
.
For example, {x for x in range(10)}
creates the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
.
s = {x for x in range(10)} print(s) # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
You can optionally add a condition to restrict the context in {expression for element in context if condition}
.
For example, {x for x in range(10) if x>5}
creates the set {6, 7, 8, 9}
.
s = {x for x in range(10) if x>5} print(s) # {6, 7, 8, 9}
💡 Learn More: Python Set Comprehension
Generator Expression
A generator function is a Pythonic way to create an iterable without explicitly storing it in memory. This reduces memory usage of your code without incurring any additional costs.
The following generator expression shows how you can use a list-comprehension like statement but pass it into the sum()
function that expects an iterable:
print(sum(random.random() for i in range(1000)))
The code consists of the following parts:
- The
print()
function prints the result of the expression to the shell. - The
sum()
function sums over all values in the following iterable. - The generator expression
random.random() for i in range(1000)
generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.
This way, we still don’t store the whole list of 1000 numbers in memory but create them dynamically.
There are two big advantages to using a generator:
- (1) You don’t have to create a huge list first and store it in memory but generate the next element as you iterate over it.
- (2) It’s shorter and more concise.
💡 Learn More: Python One Line Generator
Tuple Comprehension
Tuple comprehension such as (x+100 for x in range(3))
does not exist in Python for two main reasons:
- Ambiguity: The expression
(x+100 for x in range(3))
for tuple comprehension would be ambiguous because of the parentheses(...)
. It could also mean “create a generator expression and use the precedence as indicated by the parenthesis”. In that case, Python wouldn’t know if it should return a tuple or a generator. This is the main reason why tuple comprehension doesn’t exist. - Python Style: If you want to dynamically create a container data structure and fill it with values, you should use lists. Lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.
#python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.
— Raymond Hettinger (@raymondh) April 17, 2013
Tuple Comprehension Alternatives
You can use the following alternatives instead of tuple comprehension:
- tuple(
x+100 for x in range(3)
) creates the tuple (100, 101, 102) using a generator expression. (1, *[x+100 for x in range(3)])
creates the tuple(1, 100, 101, 102)
combining manual tuple creation with list comprehension.
You can find those two examples in the following code snippet:
# Tuple Comprehension Alternative 1 t = tuple(x+100 for x in range(3)) print(t) # (100, 101, 102) # Tuple Comprehension Alternative 2 t = (1, *[x+100 for x in range(3)]) print(t) # (1, 100, 101, 102)
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.