The purpose of this article is to follow up on my previous article, Understanding map, filter, and zip in Python, and show you a more concise way of similar functionality.
In the previous article, I covered
filter, so now I can show you how we can emulate the same functionality with list comprehensions.
Have a look at the structure of a comprehension here. Its comprised of 3 main parts.
numbers = [1,2,3,4,5] def square(number): return number*number
... squared_numbers =  for number in numbers: squared = square(number) squared_numbers.append(squared
... squared_numbers = map(square, numbers)
squared_numbers = [x*x for x in numbers]
Note: I use
x*x here for readability, however, you can more appropriately use the power of operator
** for this.
Lets now re-use our even or odd filter example from the last article to show how comprehensions can use a condition as well. We'll get the squared number of ONLY even numbers in our list.
... def even(number): if (number % 2) == 0: return True return False even_numbers = filter(even, numbers) even_numbers_squared = map(square, even_numbers)
... even_numbers_squared = [x**2 for x in numbers if (x % 2) == 0]
So with this you should have a basic grasp on how comprehensions work, how they're structured, and how they can help you write more concise code!