Comprehensions and module checkpoint
You asked about shorter ways to write loops, and Python delivers. Comprehensions let you create new lists (or dicts) in a single line by combining a loop and an optional filter. AI code uses them everywhere for transforming data.
Now for one of Python's most powerful features: comprehensions. They let you create new lists (or dicts) in a single line by combining a loop and an optional filter. AI code uses them everywhere for transforming data.
# List comprehensions (used everywhere in AI code)
scores = [3, 5, 1, 4, 2, 5, 3]
# Filter: keep only high scores
high_scores = [s for s in scores if s >= 4]
print(f"High scores: {high_scores}") # [5, 4, 5]
# Transform: from the text-to-sql agent
sql_query = "SELECT * FROM orders; SELECT * FROM items; "
statements = [s.strip() for s in sql_query.split(";") if s.strip()]
print(f"SQL statements: {statements}")Comprehensions create new lists in one line. The pattern is [expression for item in iterable if condition]. AI code uses these constantly for filtering and transforming data.
The same comprehension idea works for dictionaries too. Instead of square brackets, you use curly braces and provide both a key and a value.
# Dict comprehension: same idea, but creates a dictionary
names = ["alice", "bob"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # {'alice': 5, 'bob': 3}Dict comprehensions use {key: value for item in iterable}. They create dictionaries the same way list comprehensions create lists.
Quiz: Quiz
Loading practice…
Ordering exercise: Agent retry loop steps
Loading practice…
Validation checklist: Control flow checklist
Loading practice…
Checkpoint: Python essentials checkpoint
Loading practice…
Timed quiz: Python essentials speed round
Loading practice…