DEV Community

Cover image for Comprehensions in python: What are list, dict, and set comprehensions?
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»

Posted on • Originally published at Medium

Comprehensions in python: What are list, dict, and set comprehensions?

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)
Enter fullscreen mode Exit fullscreen mode

Output:

['derin', 'gnes', 'nuli', 'ga', 'derin', 'sabar', 'gnes']
Enter fullscreen mode Exit fullscreen mode

With list comprehension:

string_in_list =   ['aderin','agnes','anuli','aga','aderin','asabar','agnes']

str = [n[1:] for n in string_in_list]
print(str)
Enter fullscreen mode Exit fullscreen mode

Output:

['derin', 'gnes', 'nuli', 'ga', 'derin', 'sabar', 'gnes']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

['aga']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[’aga’]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'aderin': 17, 'anuli': 29, 'asabar': 25}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'aderin': 17, 'anuli': 29, 'asabar': 25}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'anuli': 29, 'asabar': 25}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'anuli': 29, 'asabar': 25}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'anuli', 'aderin', 'agnes', 'aga', 'asabar'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'agnes', 'aga', 'asabar', 'anuli', 'aderin'}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
geraldew profile image
geraldew

Do you perhaps have some line breaks missing? That:

string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']str = []
Enter fullscreen mode Exit fullscreen mode

should be:

string_in_list = ['aderin','agnes','anuli','aga','aderin','asabar','agnes']
str = []
Enter fullscreen mode Exit fullscreen mode

and similar elsewhere in the code examples.

Collapse
 
ezinne_anne profile image
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»

Oops, thank you for pointing it out.

Collapse
 
xtofl profile image
xtofl

Comprehensions are not beginner-friendly

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.

Collapse
 
ezinne_anne profile image
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»

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.

Collapse
 
xtofl profile image
xtofl

Thanks! I'm interested in the research for it turns my world view upside down.