List Comprehensions in Python

List Comprehensions in Python

Today let's talk about List Comprehensions in python.

List comprehension is a way of writing python code to solve an existing problem in a similar way as we can do it in conventional for loop but it allows us to do that inside the list with or without if condition. In the race of clean code List comprehension will always win as it achieves more readability as it almost feels like the telling what we are doing in simple plain english. Which is the beauty of python at it's core.

For example:

numbers = [10, 45, 34, 89, 34, 23, 6]
square_numbers = map(lambda num: num**2, numers)

And in List Comprehension version

square_numbers = [num**2 for num in numbers]

As you might have noticed, the List comprehension version is much more readable compared to the filter and map versions. The official Python documentation also recommends that we should use List comprehension instead of filter and map.

To further illustrate the point of using list comprehension over a for loop, let's take a look at following example where we are trying to identify vowels from list of characters.

list_char = ["t","e","c","h","y","o","w","l","s"]
vowel = ["a", "e", "i", "o", "u"]
only_vowel = []
for item in list_char:
    if item in vowel:
        only_vowel.append(item)

And the same thing can be achieved using List Comprehension in more elegant way.

[item for item in list_char if item in vowel]

In Short:

  • This example is much more readable when using list comprehension compared to using a loop but with fewer lines of code.

  • A loop has an extra performance cost because we need to append the item into the list each time, which we don’t need to do in list comprehension.

  • Filter and map functions have an extra cost to call the functions compared to list comprehension

Don’t Make Complex List Comprehension :

We also want to make sure that the list comprehension is not too complex, which can hamper our code readability and make it prone to errors. List comprehension is good for at most two loops with one condition. Beyond that, it might start hampering the readability of the code.

Avatar
Moshiour Rahman
Software Architect

My interests include enterprise software development, robotics, mobile computing and programmable matter.

comments powered by Disqus
Next
Previous