List Comprehension in Python

David Hariri
Nov 1, 2021

Say you need to iterate through a list of objects and make a new list with the value of a property of each object:

@dataclass
class Product:
sku: int
products: List[Product] = [Product(sku=1), Product(sku=2)]

You may decide to do it like this:

product_skus = []for product in products:
product_skus.append(product.sku)

And that’s fine. But you could also do it like this, with list comprehension:

product_skus = [p.sku for p in products]

This syntax is simpler to write and still very legible. This is what is meant by “Pythonic”. You can play with this code on Repl.it.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

David Hariri
David Hariri

Written by David Hariri

Designer, Programmer & Co-founder of Ada

No responses yet

Write a response