DEV Community

Cover image for Beginner Python List Comprehensions
Patrick Hanford
Patrick Hanford

Posted on

Beginner Python List Comprehensions

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
Enter fullscreen mode Exit fullscreen mode

Using a loop to square

...
squared_numbers = []
for number in numbers:
    squared = square(number)
    squared_numbers.append(squared
Enter fullscreen mode Exit fullscreen mode

Using map()

...
squared_numbers = map(square, numbers)
Enter fullscreen mode Exit fullscreen mode

Using a list comprehension

squared_numbers = [x*x  for x in numbers]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Using comprehensions

...
even_numbers_squared = [x**2 for x in numbers if (x % 2) == 0]
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker

I love using these one liners for simple tasks!