
Comprehensions are used to create new collections (list, tuple, sets, dictionary) in a clean and readable way by converting a for-loop into a concise one-liner.
There are four types of comprehensions:
- List Comprehension 
- Dict Comprehension 
- Set Comprehension 
- Generator Comprehension 
List Comprehension
It’s used to create a list by applying the desired logic. Instead of appending to a new list:
squared = []
for value in range(5):
    squared.append(value * value)You can write it as a one-liner:
squared = [x*x for x in range(5)]
# Output: [0, 1, 4, 9, 16]If we want to add in if/else statements, we can do so within our list comprehension:
list2 =  [x * x for x in range(5) if x > 2]
# Output: [9, 16]
list3 =  [x * x if x > 2 else x for x in range(5)] 
#Output: [0, 1, 2, 9, 16]Dict Comprehension:
We can create dictionaries using dictionary comprehension as well.
Basic Syntax:

Suppose that we wanted to convert a tuple into a dictionary. With dict comprehension, we can do it in one-line:
tuples = [(1,'a'),(2,'b'),(3, 'c')]
output = {x : y for x, y in tuples}
# {1 : "a", 2 : "b", 3 : "c"}We can also make a dictionary out of two lists using zip function which pairs two iterables (like lists, tuples): one for keys and one for values.
output = {k : v for k, v in zip(['x', 'y', 'z'], [2, 3, 4])}
# {'x': 2, 'y': 3, 'z': 4}A really good use case for this is if you need to switch key/value pairs in a dictionary:
original = {"one" : 1, "two" : 2, "three" : 3}
switched = {value : key for key, value in original.items()}
# {1: 'one', 2: 'two', 3: 'three'}Set Comprehension:
Similar to lists, set comprehension is written the same way. The main differentiator here is that set comprehension de-duplicates the data:
set1 = {x * x for x in range(5) if x > 2} Generator Comprehension:
Generator Comprehension is used when we are dealing with large data. Other comprehensions store all of their data in memory once they start running, which is not memory efficient.
Generator Comprehension implements the concept of lazy evaluation by creating only one item at a time which saves memory.
If we were to take a look to see which is more memory efficient:
import sys
# List comprehension
nums_list = [n**2 for n in range(1000)]
# Generator comprehension
nums_gen = (n**2 for n in range(1000))
print(sys.getsizeof(nums_list))  # large (~8696 bytes)
print(sys.getsizeof(nums_gen))   # tiny (~112 bytes)The result shows that list comprehension used approximately 8696 bytes whereas generator comprehension used 112 bytes only.
When you don’t want to use comprehensions
Avoid using comprehensions when:
- The logic is complicated, such as a double nested loop; longer comprehensions are not easy to read. 
- Multiple operations have to be performed in one iteration. 
- You require exception handling. 
Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
- Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above. 
- Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email. 
- Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away. 
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.


