Introduction:
We use comprehensions in simplifying code. If you take part in coding challenges like code wars, you would see answers using comprehensions. With comprehensions, it is possible to write one-liners instead of writing multiple lines of code in programming.
In this article, we are going to look into comprehensions in python, which includes list comprehension, dict comprehension, and set comprehension.
What is a list comprehension?
A list comprehension is a simpler and shorter way of writing code using a list. This could include a for loop and an if statement.
Example:
Letβs remove the first characters of a string from a list
Without list comprehension:
string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']
str = []
for i in string_in_list:
str.append(i[1:])
print(str)
Output:
['derin', 'gnes', 'nuli', 'ga', 'derin', 'sabar', 'gnes']
With list comprehension:
string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']
str = [n[1:] for n in string_in_list]
print(str)
Output:
['derin', 'gnes', 'nuli', 'ga', 'derin', 'sabar', 'gnes']
In the example above, list comprehension makes the code simpler and shorter.
In another example, we will select strings that are less than or equal to 3 only.
Without list comprehension
string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']
str = []
for i in string_in_list:
if len(i) <= 3:
str.append(i)
print(str)
Output:
['aga']
Using list comprehension, we will simplify and shorten the code.
string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']
str = [n for n in string_in_list if len(n) <= 3]
print(str)
Output:
[βagaβ]
Now, letβs look at dict comprehension.
What is dict comprehension?
Dict comprehensions are used to simplify and shorten dictionaries. Dict comprehensions can accept a for loop and an if statement, too.
Without dict comprehension
str_in_dict = {βaderinβ:23,βagnesβ:26,βanuliβ:29,βagaβ:31,βaderinβ:17,βasabarβ:25,βagnesβ:37}
bio_str = {}
for k,v in str_in_dict.items():
if v <= 30:
bio_str[k] = v
print(bio_str)
Output:
{'aderin': 17, 'anuli': 29, 'asabar': 25}
With dict comprehension
str_in_dict = {βaderinβ:23,βagnesβ:26,βanuliβ:29,βagaβ:31,βaderinβ:17,βasabarβ:25,βagnesβ:37}
bio_str = {k: v for (k,v) in str_in_dict.items() if v <= 30}
print(bio_str)
Output:
{'aderin': 17, 'anuli': 29, 'asabar': 25}
In the code above, we added ages to the name strings and looped through the names and select only the names with ages that are less than or equal to 30.
If we want to select ages that are greater than 20 and less than 30, we could add one more if statement to the previous code.
Without dict comprehension
str_in_dict = {βaderinβ:23,βagnesβ:26,βanuliβ:29,βagaβ:31,βaderinβ:17,βasabarβ:25,βagnesβ:37}
bio_str = {}
for k,v in str_in_dict.items():
if v <= 30 and v >= 20:
bio_str[k] = v
print(bio_str)
Output:
{'anuli': 29, 'asabar': 25}
With dict comprehension
str_in_dict = {βaderinβ:23,βagnesβ:26,βanuliβ:29,βagaβ:31,βaderinβ:17,βasabarβ:25,βagnesβ:37}
bio_str = {k: v for (k,v) in str_in_dict.items() if v <= 30 if v >= 20 }
print(bio_str)
Output:
{'anuli': 29, 'asabar': 25}
What is a set comprehension?
A set comprehension is a simpler, shorter form of sets. Like dict comprehensions, they use curly brackets.
Sets do not produce duplicate values, unlike lists, so it produces unique values when we loop through them.
Without set comprehension
strings_in_set= {βaderinβ,βagnesβ,βanuliβ,βagaβ,βaderinβ,βasabarβ,βagnesβ}
bio_sets = set()
for i in strings_in_set:
bio_sets.add(i)
print(bio_sets)
Output:
{'anuli', 'aderin', 'agnes', 'aga', 'asabar'}
With set comprehension
strings_in_set = {βaderinβ,βagnesβ,βanuliβ,βagaβ,βaderinβ,βasabarβ,βagnesβ}
bio_sets = {i for i in strings_in_set}
print(bio_sets)
Output:
{'agnes', 'aga', 'asabar', 'anuli', 'aderin'}
When to use comprehensions
Comprehensions are not beginner-friendly but once you gain an understanding of lists, dictionaries, and sets. You would love them. Especially for their simple style, it is not always advisable to use comprehensions. They might be difficult to read.
In the poem titled Zen of Python, there is a line that says,
if the implementation is hard to explain, itβs a bad idea.
When using comprehensions, you will write it and feel like itβs easy to explain, but thatβs because you wrote it. It may be completely hard for someone else who looks at your code to understand what you are doing.
Conclusion
Comprehensions are used to simplify and shorten code. When writing code and you realize you are using too many lines, then you could use comprehensions. But it should be easy to read and understand.
Thank you for reading and cheers to more learning.
Top comments (5)
Do you perhaps have some line breaks missing? That:
should be:
and similar elsewhere in the code examples.
Oops, thank you for pointing it out.
I wonder. I think it depends on how the beginner has begun. Do you happen to have any research on that statement? Because I can hardly believe that a beginner would have more trouble reading
[x*x for x in numbers]
than with the 4-liner you would need, unless they already have been trained to recognise it as a pattern.Comprehensions are not beginner-friendly especially for folks that are new to programming. It maybe easier for folks coming from other languages, and yes I did research.
Thanks! I'm interested in the research for it turns my world view upside down.