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.

--

--