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

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)

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.