Beginner Python List Comprehensions

codespent

Patrick Hanford

Posted on December 31, 2019

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!

💖 💪 🙅 🚩
codespent
Patrick Hanford

Posted on December 31, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024