DEV Community

Cover image for Beginner Python List Comprehensions

Beginner Python List Comprehensions

codespent profile image Patrick Hanford ・1 min read

Python comprehensions

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.

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.

Alt Text

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)

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]


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!

Discussion (2)

oliverandrich profile image
Oliver Andrich

Nice article. I especially like the graphics. Helpful when I have to explain this next time to someone.

waylonwalker profile image
Waylon Walker

I love using these one liners for simple tasks!

Forem Open with the Forem app