g↗genai/ learner
Python for AI / Lesson 04

Lists

AI pipelines process sequences of data: retrieved search passages, chat turn histories, candidate completions, and token IDs. In Python, lists provide the foundational ordered, mutable sequence to store, slice, and manipulate these collections in memory.

Concept + interactive labBeginner friendly

Ordered sequences: Constructing lists for AI pipelines.

In Python, a list (type list) is an ordered collection of items enclosed in square brackets [...], separated by commas.

Think of a list as a numbered clipboard: each item occupies a specific sequential slot. In an AI Retrieval-Augmented Generation (RAG) system, a search retriever returns a list of candidate passages ranked by relevance:

# A list of retrieved document passage IDs:

retrieved_docs = [
  "refund_policy",
  "shipping_faq",
  "order_tracking",
  "warranty_terms",
]

You can check how many items are stored in a list using the built-in len() function:

total_candidates = len(retrieved_docs) # Evaluates to int 4

Educational 3-panel diagram illustrating Python list memory and operations: Panel 1 shows dual indexing for a 4-item list with 0-based positive indices 0, 1, 2, 3 from the head and negative indices -4, -3, -2, -1 from the tail. Panel 2 shows context window slicing docs[1:3] extracting items at indices 1 and 2 ('shipping_faq' and 'order_tracking') and stopping before index 3. Panel 3 contrasts in-place mutation docs.append('profile') adding an item to the existing list in memory against the fatal rebinding bug docs = docs.append(...) which destroys the reference and rebinds the variable to None.
Figure 1: Core concepts of Python lists: 0-based positive and negative tail indexing, slicing sublists for prompt token budgets, and in-place mutation versus the variable rebinding trap.

Indexing: Accessing elements from head and tail.

To access an individual item inside a list, write the list name followed by the item's position index inside square brackets: docs[i].

In Python, sequences use 0-based indexing. The first element is located at index 0, not 1:

top_match = retrieved_docs[0] # Evaluates to "refund_policy"

second_match = retrieved_docs[1] # Evaluates to "shipping_faq"

When building AI pipelines, you frequently need the newest message in a conversation or the lowest-ranked candidate in a pool. Python provides negative indexing to count backward from the tail:

  • docs[-1]: Accesses the last item (e.g. "warranty_terms").
  • docs[-2]: Accesses the second-to-last item (e.g. "order_tracking").
Valid Index Range: For any non-empty list, valid indices lie in the inclusive range between -len(docs) and len(docs) - 1. Attempting to access an index outside this range (such as retrieved_docs[10] on a 4-item list) immediately crashes your pipeline with IndexError: list index out of range.

List Structure: Slots & Dual Indices

Ordered Mutable Sequence

retrieved_docs[0] or retrieved_docs[-4] → "refund_policy"

Every list item can be reached via positive indexing from head (0 to 3) or negative indexing from tail (-1 to -4).

Slicing: Extracting sublists for prompt context budgets.

LLMs have finite context windows and cost budgets. Even if a vector database returns dozens of matching documents, you might only have space in your prompt for the top 2 passages. (Note: Slicing extracts items strictly by sequential position; it does not measure tokens. Model tokenizers measure token counts, while slicing provides an architectural cutoff assuming top-ranked passages fit the budget.)

Python allows you to extract a sublist using slicing syntax: docs[start : stop]. Slicing starts at index start (inclusive) and stops before index stop (exclusive):

# Extract top 2 passages (indices 0 and 1):

context_docs = retrieved_docs[0:2]

# Evaluates to: ["refund_policy", "shipping_faq"]

You can omit bounds when starting from the head or slicing to the tail:

  • docs[:2]: Omit start to begin from index 0 (first 2 items).
  • docs[2:]: Omit stop to slice from index 2 all the way to the end.
  • docs[-2:]: Extract the final 2 elements from the tail.
Slicing Out-of-Bounds Never Crashes: While single indexing (docs[10]) throws an IndexError, Python handles out-of-range slice bounds gracefully. Writing docs[:10] on a 4-item list simply returns all 4 items without raising an error. When slice bounds are non-negative, any slice where start >= stop yields an empty list []. (When negative bounds are used, Python first converts them to positive offsets by adding len(docs), so docs[0:-1] cleanly returns all items except the last.)

Mutability: In-place updates and the .append() trap.

In Lesson 03, we learned that strings are immutable: transformative methods like .replace() and .strip() return new strings, leaving the original intact. Lists in Python are the opposite: they are mutable.

You can add items to the end of an existing list using the .append() method, remove items with .pop(), or update any slot directly:

# 1. Mutate in place by appending a new context string:

retrieved_docs.append("user_profile")

# retrieved_docs now has 5 items in memory.
# 2. Update an outdated passage at slot 1 in place:

retrieved_docs[1] = "shipping_v2"

# 3. Remove and return the tail item:

removed = retrieved_docs.pop()

# removed is "user_profile"; len is back to 4.
The Fatal .append() Rebinding Trap: In Python, .append() mutates the list in place and returns None. If you write:
docs = docs.append("new_doc")
the list is modified, but your variable name tag docs is rebound to the return value None! Subsequent attempts to call docs.append(...) fail with AttributeError: 'NoneType' object has no attribute 'append', and slicing docs[:2] fails with TypeError: 'NoneType' object is not subscriptable. Always call docs.append(...) by itself without reassignment!

Inspect list operations in the AI context sandbox.

Experiment with how positive and negative indices, context window slicing bounds, in-place appends, and the .append() rebinding trap behave in a simulated RAG pipeline:

AI List & Context Sandbox

Inspect how Python lists store ordered RAG candidates, slice prompt context budgets, mutate in place via .append() and .pop(), and recover from the variable rebinding trap.

Presets:
retrieved_docs:len(retrieved_docs) = 4

Index Inspector (Click any slot above or select an index)

retrieved_docs[0] (head) or retrieved_docs[-4] (tail) evaluates to: "refund_policy"

Context Budget Slicing: retrieved_docs[start : stop]

Yields 2 items
context_docs = retrieved_docs[0:2]
Result: ["refund_policy", "shipping_faq"] (2 items)

In-Place Mutation Controls

Remove / Modify Slot:
Last operation:Loaded preset: RAG Candidates (4 items)
Try it in this order:
  1. Click any slot in retrieved_docs above to inspect its positive index (+i) and negative index (-i) in the Index Inspector.
  2. Change Stop index to 2. Notice that [0:2] selects the first 2 items (indices 0 and 1) and stops before 2.
  3. Click .append() to add "user_profile". See the list mutate in place to length 5, and note how negative indices dynamically adjust.
  4. Click Trigger Bug: docs = docs.append(). Observe how the variable name tag is rebound to None, abandoning the list reference, even though the underlying list was mutated! Click Restore reference (Simulation demo) to recover the reference and verify the list preserved the appended item.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

An AI engineer prepares candidate documents for a prompt and writes: candidates = ['doc_billing', 'doc_returns', 'doc_shipping'] candidates = candidates.append('doc_warranty') top_candidates = candidates[:2] What happens when this Python code executes?
THE TAKEAWAY

Take this with you.

Python lists (list) are ordered, mutable sequences fundamental to AI workflows. Access items from the head using 0-based positive indexing (docs[0]) and from the tail using negative indexing (docs[-1]). Slice sublists for prompt context budgets with docs[start:stop], which stops before stop and gracefully handles out-of-range bounds. Remember that lists are mutable: methods like .append() modify the list in place and return None. Never assign the result of .append() back to your variable!

Next up: Tuples and Sets in Chapter P1 →