As one of the most iconic Pythonic syntax in the language, I’m sure everyone has heard of or used list comprehension.

But did you know that there are three other types of comprehension in this language?

In this article, I’ll discuss what comprehensions are in Python and why you should use them. I’ll also discuss when using comprehension can adversely affect the readability of code.

What is understanding in Python?

Essentially, comprehension in Python is a syntax for creating a new sequence by operating on another iterated object.

There are four types of understanding in Python.

  1. List comprehensions
  2. Dict assembly
  3. Set understanding method
  4. Generator understanding

A common misconception most beginners have about understanding is that the initial iteration object needs to be of the same type as understanding. However, this is not the case; for example, if you are using a dict compiler, the initial iterator can also be a list.

The type mentioned in the name refers to the type of the sequence returned from comprehension.

Why use comprehension in Python?

We use comprehension in our code because it is more Python and readable. However, they need to be used with care in certain situations, as sometimes they can have the opposite effect.

List comprehensions

List comprehension is the most common type of comprehension in Python, and it follows simple syntax.

# Not using conditional in list comprehension.
[<expression> for <variable> in <iterable>]

# Using standard condition in list comprehension.
[<expression> for <variable> in <iterable> if <condition>]

# Using if and else in a list comprehension.
[<expression>  if <condition> else <expression> for <variable> in <iterable>]
Copy the code

As we see here, the condition is completely optional, but if you use it, its position in the list understanding will change depending on whether you use the else clause.

We can also see that they are very easy to use and quite handy in reducing the use of the for loop, making the code much cleaner.

The best way to master them is to play with them yourself and understand their limitations. Here’s a real-world example to give you an idea.

original_list = ["hello"."and"."welcome"."to"."list"."comprehensions"]

# Not using conditional in list comprehension.
new_list = [item.capitalize() for item in original_list]
print(new_list)
# ['Hello', 'And', 'Welcome', 'To', 'List', 'Comprehensions']

# Using standard condition in list comprehension.
new_list = [item.capitalize() for item in original_list if item not in ["and"."to"]]
print(new_list)
# ['Hello', 'Welcome', 'List', 'Comprehensions']

# Using if and else in a list comprehension.
new_list = [item.capitalize() if item not in ["and"."to"] else item for item in original_list]
print(new_list)
# ['Hello', 'and', 'Welcome', 'to', 'List', 'Comprehensions']
Copy the code

Dict understand

As I mentioned earlier, the type referred to in a comprehension name refers to the type of the sequence it creates, not the type of the iterator used in comprehension.

head -n 10 us.txtThe syntax for a dictionary comprehension is:
Copy the code
new_dictionary = {<key>:<value> for <item> in <iterable> if <condition>}
Copy the code

Again, the conditions here are optional.

You can use it in many different scenarios, for example, imagine that you want to be able to compare the salaries of employees based on their positions in the company, and you have a long list of dictionaries containing various information about each employee.

In fact, you may be able to use it for work, but if you only care about job titles and salaries, there is a lot of information that is not needed, so we can easily use dictionary understanding to create a new dictionary that contains only the information we want.

employee_list = [
    {
        'name': 'Peter'.'surname': 'Pan'.'position': 'Full-stack Developer'.'salary': 60000
    },
    {
        'name': 'Molly'.'surname': 'Weasley'.'position': 'Front-End Developer'.'salary': 50000
    },
    {
        'name': 'Harry'.'surname': 'Potter'.'position': 'Data Scientist'.'salary': 55000
    },
    {
        'name': 'Hermione'.'surname': 'Granger'.'position': 'Data Engineer'.'salary': 50000
    },
    {
        'name': 'Ronald'.'surname': 'Weasley'.'position': 'Junior Developer'.'salary': 40000}]# Dict Comprehension without condition.

position_dict = {position['position']: position['salary'] for position in employee_list}
print(position_dict)
# {'Full-stack Developer': 60000, 'Front-End Developer': 50000, 'Data Scientist': 55000, 'Data Engineer': 50000, 'Junior Developer': 40000}

# Dict Comprehension with condition.

position_dict = {position['position']: position['salary'] for position in employee_list if "Developer" in position['position']}
print(position_dict)
# {'Full-stack Developer': 60000, 'Front-End Developer': 50000, 'Junior Developer': 40000}
Copy the code

As you can see above, we can achieve this goal very easily and cleanly in one line with the understanding of a dictionary *. *

A collection of understanding

Collection comprehension functions like list comprehension, except that it has all the advantages of collections, namely that the items in the collection cannot be repeated and the values are not in order.

In addition to using curly braces instead of square brackets, it uses similar syntax to list comprehension.

# Not using conditional in set comprehension.
{<expression> for <variable> in <iterable>}

# Using standard condition in set comprehension.
{<expression> for <variable> in <iterable> if <condition>}

# Using if and else in a set comprehension.
{<expression>  if <condition> else <expression> for <variable> in <iterable>}
Copy the code

This can be useful in some cases, but you have to remember to be careful because the positive aspects of the collection can cause problems if you need to sort the results, as shown below.


original_list = ["hello"."and"."welcome"."to"."set"."comprehensions"."set"."comprehensions"]

# Not using conditional in set comprehension.
new_set = {item.capitalize() for item in original_list}
print(new_set)
# {'To', 'Hello', 'Set', 'And', 'Welcome', 'Comprehensions'}

# Using standard condition in set comprehension.
new_set = {item.capitalize() for item in original_list if item not in ["and"."to"]}
print(new_set)
# {'Set', 'Comprehensions', 'Hello', 'Welcome'}

# Using if and else in a set comprehension.
new_set = {item.capitalize() if item not in ["and"."to"] else item for item in original_list}
print(new_set)
# {'Hello', 'Set', 'and', 'to', 'Welcome', 'Comprehensions'}
Copy the code

Generator understanding method

Generator understanding is the least known type of understanding we have in Python.

A generator is a function that returns an object (an iterator) that we can iterate over one by one. It is a unique syntax in Python and is usually generated by a function with the yield keyword.

The generator syntax is as simple as any other syntax.

# Not using conditional in generator comprehension.
(<expression> for <variable> in <iterable>)

# Using standard condition in generator comprehension.
(<expression> for <variable> in <iterable> if <condition>)

# Using if and else in a generator comprehension.
(<expression>  if <condition> else <expression> for <variable> in <iterable>)
Copy the code

The advantage of using a generator is that we can iterate over it step by step using the built-in function **next()**.

generator = (i*2 if i%2 else i**2 for i in range(0.10))
for _ in range(10) :print(next(generator), end=' ')
    
# 0 2 4 6 16 10 36 14 64 18 
Copy the code

When should you not use a compiler?

After reading everything here, it doesn’t seem necessary to always use comprehension, right?

It’s not.

Comprehensions in Python can be used in all of the above ways to create readable code, but we need to be careful when using nested comprehensions, because it can cause code to become less readable.

Nested understanding

Nested understanding is a term we use to refer to understanding within other understandings.

While this is a very powerful feature, it can also have the opposite effect in terms of readability.

For example, the following two scripts both create the following pyramids.

# method 1

for row in range(0, number_of_rows):
    for _ in range(0, row + 1) :print("#", end=' ')
    print("\n")    
    
# Method 2

print('\n'.join([' '.join([The '#' for _ in range(1, row + 1)]) for row in range(0, number_of_rows)]))
Copy the code
#
##
###
####
#####
######
#######
Copy the code

As we can see, although this is a fairly basic example, it is already very readable without nested understanding, and as complexity increases, it becomes more difficult to maintain readability with these.

Through this article and our understanding of comprehensibility, we cannot fully appreciate the power they bring to language, but at the same time, we need to be careful not to abuse them, because when logic is not simple, readability can quickly be adversely affected.

I always like to remember this simple phrase whenever I start nesting understanding myself.

Code should interpret comments, not comments that explain code.

Then decide if it’s best to write logic instead of comprehension.

The great thing about using comprehension is that, if used properly, it can help you produce efficient and readable code.

I hope you enjoy reading and keep learning