Data Structures for AI
Lists & Tuples
3 min read
Lists and tuples are ordered collections in Python. They're fundamental for AI work—you'll use them to store conversation history, tool results, and much more.
Lists: Mutable Collections
Lists can be modified after creation.
# Creating lists
messages = ["Hello", "How are you?", "I'm fine"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "text", True, 3.14]
# Accessing elements (0-indexed)
first = messages[0] # "Hello"
last = messages[-1] # "I'm fine"
# Slicing
first_two = messages[0:2] # ["Hello", "How are you?"]
Modifying Lists
messages = ["Hello"]
# Adding elements
messages.append("World") # ["Hello", "World"]
messages.insert(0, "Start") # ["Start", "Hello", "World"]
# Removing elements
messages.remove("Start") # ["Hello", "World"]
popped = messages.pop() # Returns "World", list is ["Hello"]
# Changing elements
messages[0] = "Hi" # ["Hi"]
List Comprehensions
A powerful way to create lists:
# Without comprehension
squares = []
for x in range(5):
squares.append(x ** 2)
# With comprehension (cleaner!)
squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Tuples: Immutable Collections
Tuples cannot be modified after creation—useful for fixed data.
# Creating tuples
point = (10, 20)
rgb = (255, 128, 0)
# Accessing (same as lists)
x = point[0] # 10
# Tuple unpacking
x, y = point # x=10, y=20
r, g, b = rgb # r=255, g=128, b=0
When to Use Each
| Use Case | Data Structure |
|---|---|
| Conversation messages | List (changes over time) |
| API response fields | Tuple (fixed structure) |
| Tool arguments | List or Tuple |
| Configuration values | Tuple (shouldn't change) |
Next, we'll explore dictionaries for key-value storage. :::