List Comprehensions in Python
A Complete Guide to using List Comprehensions in Python, its uses and benefits over standard loops
Beautiful is better than ugly, Flat is better than nested
The Zen of Python beautifully sums up everything there is to know about programming style.
List comprehensions in python takes this idea further by providing an elegant way of creating lists based on another list or iterator.
To better understand this concept, let’s begin with a straightforward example.
Suppose you wish to find cube of all numbers in a list and store them in a new list. Using a for loop, we can code this as follows:
However, Python provides an easier and more elegant way to solve this problem using List Comprehension.
Isn’t that amazing!
The basic syntax for list comprehension is as follows:
new_list = [ expression for element in old_list if condition]new_list
The resulting list.expression
The operation performed whenever an element fulfills the given condition, like i**3 in previous example. The result of this expression is stored in new_list.for element in old_list
Iterates over each element in old_listif condition
Apply a condition using an If-statement.
Let’s modify the previous example to include the conditional.
Perhaps, what makes list comprehension even more powerful is the ability to add as many for or if clauses as required.
Suppose you wish to find cube of the even numbers and square of the odd numbers in a list and store them in a new list. Using a for loop, we code:
Using list_comprehension, this becomes:
The beauty of list_comprehension becomes more apparent when we start considering nested for loops.
Consider a program to find the Cartesian product of two lists.
Now using list comprehension:
A final example would be to find common numbers between two lists using list comprehension:
List Comprehensions vs Lambda functions
There are various built in functions and lambda functions that can help play with lists just like list comprehensions. Let’s take an example here to double all the numbers in a list using lambda functions:
I personally find list comprehensions to be much more lucid and readable than lambda functions. What do you prefer?
List comprehension provides an elegant way of defining lists based on other existing lists.
It is generally more compact and faster as it is optimized for the Python interpreter.
If you have several nested loops, it might be a good idea to avoid writing down a very long list comprehension and stick to the normal loop syntax in favor of readability.
If you enjoyed this article, you might also like :