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.
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:
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.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fpython-lists-model.11wq8deg4akw8.jpg&w=3840&q=75)
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").
-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 Sequenceretrieved_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):
context_docs = retrieved_docs[0:2]
You can omit bounds when starting from the head or slicing to the tail:
docs[:2]: Omit start to begin from index0(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.
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:
retrieved_docs.append("user_profile")
retrieved_docs[1] = "shipping_v2"
removed = retrieved_docs.pop()
.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.
retrieved_docs:len(retrieved_docs) = 4Index 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]
In-Place Mutation Controls
- Click any slot in
retrieved_docsabove to inspect its positive index (+i) and negative index (-i) in the Index Inspector. - Change Stop index to
2. Notice that[0:2]selects the first 2 items (indices 0 and 1) and stops before 2. - Click .append() to add
"user_profile". See the list mutate in place to length 5, and note how negative indices dynamically adjust. - 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.
Check your understanding.
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!