Understanding Python Comprehensions

Understanding Python Comprehensions

Are They Easy to Comprehend?

Comprehension is a unique feature of Python. Comprehension gives us a concise way to construct sequences like lists, sets, and dictionaries.

A comprehension is a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

image.png Now you have one more option for creating sequences in Python. Using comprehension you can make your Python code more Pythonic! But remember that you want your code as easy to understand as possible.

So you should avoid longer single lines of code. In that case, it is better to break your code down into smaller lines.

If you’re familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:

List comprehension ✔

A list comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

For Loop:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

The above example implemented as a list comprehension:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

Key Points on List Comprehension

📌 List comprehension is a sublime way to define and build lists with the help of existing lists.
📌 In comparison to normal functions and loops, List comprehension is usually more compact and faster for creating lists.
📌 Remember, every list comprehension is rewritten in for loop, but every for loop can’t be rewritten within the kind of list comprehension.

Generator Comprehensions ✔

Generator Comprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets ( ) whereas list comprehensions use square brackets.

Generator comprehension does not initialize any object unlike list comprehension or set comprehension. Thus, you can use generator comprehension instead of list comprehension or set comprehension to reduce the memory requirement of the program.

Using def& for loop:

def num_generator():
    for i in range(1, 11):
        yield i

gen = num_generator()
print("Values obtained from generator function are:")

for element in gen:
    print(element)

Let's implement the above generator using a generator comprehension

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

mygen = (element**2 for element in myList)
print("Elements obtained from the generator are:")
for ele in mygen:
    print(ele)

Set Comprehension ✔

Set comprehension is pretty similar to list comprehension. The only difference is instead of using [ ] we use { }. Because we represent sets using curly brackets { } in Python.

For Loop;

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

output_set = set()

for var in input_list:
    if var % 2 == 0:
        output_set.add(var)

The above example implemented as a set comprehension:

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

set_using_comp = {var for var in input_list if var % 2 == 0}

Dictionary Comprehension ✔

Dictionary comprehension is a method for transforming one dictionary into another dictionary.

Dict comprehensions are just like list comprehensions, except that you group the expression using curly braces { } instead of square braces.

For Loop Example of doubling values;

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
double = {}

for k,v in dict1.items():
    result = k
    double[result] = v*2

The above example implemented as a dict comprehension:

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}

🔸 Are They Easy to Comprehend ?

Consider this example and judge by yourself...

numbers = [2*x if x > 2 and x < 5 else 3*x if x <=2 else 4*x for x in range(10)]

Comprehensions offer a great choice of writing code faster, easily and pythonic. However, we should always avoid writing very long list comprehensions in one line to confirm that code is user-friendly.

As you can see in the above example, if you are not familiar with them, they can be hard to understand than a normal for loopespecially those long ones. I will explain how to arrive at such a list of comprehension in the next article.

🔸 Conclusion

I will focus on list comprehensions in my next blog because we usually use more these than other comprehensions.

That's it!

If you enjoyed this article, consider subscribing to my channel for related content especially about Tech, Python & Programming.

📢Follow me on Twitter: ♥ ♥

Ronnie Atuhaire