Practical: Master and Code as a Pro with Python Comprehensions

Practical: Master and Code as a Pro with Python Comprehensions

Master the main types of python comprehensions and write in an elegant style

Python comprehension is a short elegant style of writing readable and precise python codes.

How does the python comprehension work and why should I use it?

If C programming Language was your first language, you'll realize that the for loop syntax is short and straightforward.

Don't know what I meant? Here's an example of a for loop in C language.

#include <stdio.h>

int main(void){

    for(int i=0; i<3; ++i)
    {
        printf("%d",i);
    }
    return(0);
}

The above example is a simple illustration of the for loop syntax in C...When it comes to the for loop syntax in python, it's quite different because it takes some lines to write.

Don't understand what I meant? Here's an example:

for i in range(3):
    result = i**2
    print(result)

But...What if we could make things easier by just writing a one-line code for a for loop syntax?

Isn't that a nice pythonic coding style?

Types of Python Comprehensions

There are four types of python comprehensions with examples:

List Comprehension

nums = [2,3,4,5]
my_list = [] 
for n in nums:
    my_list.append(n**2)
print(my_list)

#Output
[4, 9, 16, 25]

Here's how to use a list comprehension for the above example:

my_list = [n**2 for n in nums]
print(my_list)

#Output
[4, 9, 16, 25]

Dictionary Comprehension

# Using two lists to create a dictionary

names = ['bruce','clark','peter']
heroes = ['batman','superman','spiderman']
print(dict(zip(names,heroes)))

#Output
{'bruce': 'batman', 'clark': 'superman', 'peter': 'spiderman'}


#using for loop to create the dictionary

my_dict ={}
for name,hero in zip(names, heroes):
    my_dict[name] = hero

print(my_dict)

#Output
{'bruce': 'batman', 'clark': 'superman', 'peter': 'spiderman'}

Here's how a dictionary comprehension creates a dictionary:

my_dict = {name:hero for name, hero in zip(names,heroes)}
print(my_dict)

#Output
{'bruce': 'batman', 'clark': 'superman', 'peter': 'spiderman'}

Set Comprehension

nums = [2, 4, 3, 6, 7, 6, 6, 6, 7, 7]
my_set = set()

# Using a for loop to create a set
for num in nums:
    if num % 2 == 0:
        my_set.add(num) #adds an item to the empty set just as the append function in lists

print(my_set)

#Output
{2, 4, 6}

Here's how a set comprehension solves the example

my_set = {num for num in nums if num%2==0}
print(my_set)

#Output
{2,4,6}

Conclusion

The list, set, dictionary comprehension allows us to code in a short and elegant style. There are still a few ways of writing various comprehensions in python.

As you continue to code on your development journey, you'll become exposed to more.