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.
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?"},
]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:
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
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
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.
- Make a list of the customers' names in capital letters.
- Make a list of the lengths of each ticket's text.
- Change the
ifto keep tickets whose id is greater than 1.
Every expert started right here.