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]
The resulting list.
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_list
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 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 : Functions as Objects in Python