Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is a List Comprehension?


What you need to know

Anatomy

Python
nums = [1, 2, 3, 4, 5, 6]squares = [n * n for n in nums]                    # transformevens   = [n for n in nums if n % 2 == 0]          # filterlabels  = ["even" if n % 2 == 0 else "odd" for n in nums[:3]]   # if-else goes FIRSTprint(squares, evens, labels)# [1, 4, 9, 16, 25, 36] [2, 4, 6] ['odd', 'even', 'odd']

It is the same as:

Python
evens = []for n in nums:    if n % 2 == 0:        evens.append(n)

Two different ifs: an if at the end filters items out; an if ... else at the front is a conditional expression that chooses a value for every item.

The family

Python
words = ["UPI", "upi", "Refund"]print({w.lower() for w in words})              # set:  {'upi', 'refund'} (order may vary)print({w: len(w) for w in words})              # dict: {'UPI': 3, 'upi': 3, 'Refund': 6}total = sum(len(w) for w in words)             # generator expression: no list builtprint(total)                                   # 12

A generator expression uses round brackets and produces items one at a time. Use it when you only need to consume the values once, like inside sum, max or any, and the data may be large.

Nested loops

[x for row in matrix for x in row] flattens a list of lists. The for clauses read in the same order as nested loops would. One level of nesting is fine; two or more is hard to read.

A real-life example

Before sending scraped FAQ text to an LLM, you clean it: strip whitespace, drop empty and very short lines, and collapse repeated spaces. Then you build one prompt per chunk:

Python
raw = """  How do I reset my UPI PIN?   Go to   Settings > UPI  and tap Reset.okRefunds are credited in 5-7 working days.  """lines = [" ".join(line.split()) for line in raw.splitlines() if len(line.strip()) > 3]print(lines)# ['How do I reset my UPI PIN?', 'Go to Settings > UPI and tap Reset.', 'Refunds are credited in 5-7 working days.']prompts = [f"Rewrite for a customer, in one sentence:\n{line}" for line in lines]approx_tokens = sum(len(p) // 4 for p in prompts)    # rough rule: ~4 characters per tokenprint(len(prompts), approx_tokens)                   # 3 55

The comprehension says what is kept and how it is transformed, in one line each. The sum(... for ...) estimate never builds a list. For a million chunks, this pattern is also noticeably faster than the equivalent append loop.

Follow-up questions to expect

  • "List comprehension vs generator expression?" — The list version builds the whole list in memory; the generator version yields items lazily and can be consumed only once.
  • "Is it faster than a loop?" — Usually somewhat, because it avoids the repeated .append lookup. The main benefit is readability.
  • "Do comprehension variables leak?" — No. In Python 3 a comprehension has its own scope, so the loop variable is not visible afterwards.