Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

List comprehensions: a new list in one line

Lesson 9 built a list with an empty list, a loop and append. That pattern is so common that Python has a one-line form for it, used all over AI code.

Examplethe tickets from lesson 9
tickets = [
    {"id": 1, "customer": "Asha", "text": "I was charged twice for one order"},
    {"id": 2, "customer": "Ben", "text": "My parcel has not arrived"},
    {"id": 3, "customer": "Chen", "text": "Can I get a refund for the blue mug?"},
]
Example
texts = []
for ticket in tickets:
    texts.append(ticket["text"])
print(texts)

Four lines to collect one field. Here is the same list as a list comprehension:

Example
texts = [ticket["text"] for ticket in tickets]
print(texts)

Read the brackets as: a list of ticket["text"], for each ticket in tickets. The part before for is what goes into the new list.

Keeping some of them

Example
ids = [ticket["id"] for ticket in tickets if "refund" in ticket["text"].lower()]
print(ids)

An if at the end keeps only the items that pass, like the filter in lesson 9.

A dictionary the same way

Example
customers = {ticket["id"]: ticket["customer"] for ticket in tickets}
print(customers)
print(customers[2])

Curly brackets and a key: value pair make a dictionary instead. Looking a customer up by id is now one step instead of a loop.

When to use a plain loop instead: when the loop prints, counts, or does more than one thing per item. A comprehension that needs a second line of thought is easier to read as a loop.

Try it yourself
  • Make a list of the customers' names in capital letters.
  • Make a list of the lengths of each ticket's text.
  • Change the if to keep tickets whose id is greater than 1.

Every expert started right here.