List Comprehension

noun

say it: “LIST kom-prih-HEN-shun” /lɪst ˌkɑmprɪˈhɛnʃən/

A one-line way to build a new list from another collection, in square brackets, optionally keeping only the items you want.

What is a list comprehension?

A list comprehension builds a new list from another collection in one line, optionally keeping only the items you want.

prices = [10, 25, 40]
with_tax = [price * 1.07 for price in prices]
cheap = [price for price in prices if price < 30]
print(cheap)  # [10, 25]

In a sentence

  • “A list comprehension with an if kept only the prices under $30.”
  • “The list comprehension [price * 1.07 for price in prices] adds tax to every price.”

Level: Journeyman · More Python terms at this level

Updated