• PyByte
  • Posts
  • 👩‍💻 What is List Comprehension in Python?

👩‍💻 What is List Comprehension in Python?

Sign up for a Live Python Class in December!

from PyByte import deep_dive

# Welcome to the PyByte!

Analyzing Toy Story GIF by Giflytics

Gif by Giflytics on Giphy

Ever wanted to learn data cleaning in Python? To celebrate the holidays (and the end of 2023) I’m hosting a LIVE training sometime in December (TBD)!

It will be 60 minutes of taking a dataset with a LOT of problems and then building a script to fix it’s many problems!

deep_dive()

If you want your Python code to be more concise and more Pythonic, list comprehension offers a succinct and efficient way to create lists.

This method not only reduces the lines of code but also makes your code more readable and expressive (effectively communicates its purpose).

Here's a quick guide to using list comprehensions:

Basic Syntax

The basic structure of a list comprehension is:

[expression for item in iterable]

This replaces the need for multi-line loops to populate a list, like this:

squares = []
x in range(5):
    squares.append(x**2)

print(squares)  # Output: [0, 1, 4, 9, 16]

Let’s convert this multi-line loop into a single line of code 🤯:

squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

You can also include conditions in a list comprehension. Notice this time I use range(10) which is numbers 0 through and including 9.

evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # Output: [0, 2, 4, 6, 8]

Next time you need to generate a list from an iterable, reference this guide and try list comprehension!

See you next week 👋

Joel