Patrick Hanford

Posted on

# Python comprehensions

## List Comprehensions

In the previous article, I covered `map` and `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
``````

#### Using a loop to square

``````...
squared_numbers = []
for number in numbers:
squared = square(number)
squared_numbers.append(squared
``````

#### Using map()

``````...
squared_numbers = map(square, numbers)
``````

#### Using a list comprehension

``````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. `[x**2]`.

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.

#### Using filter() and map()

``````...
def even(number):
if (number % 2) == 0:
return True
return False

even_numbers = filter(even, numbers)
even_numbers_squared = map(square, even_numbers)
``````

#### Using comprehensions

``````...
even_numbers_squared = [x**2 for x in numbers if (x % 2) == 0]
``````

## Conclusion

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!