06. Lists and List Comprehensions

Chapter 6 of 36 · 20 min

Creating Lists

models = ["gpt-4", "gpt-3.5-turbo", "claude-3"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, None]

List Operations

models.append("llama-2")      # Add to end
models.insert(0, "mistral")  # Insert at position
models.remove("gpt-4")       # Remove by value
popped = models.pop()        # Remove and return last item

Slicing

first_three = numbers[:3]     # [1, 2, 3]
last_two = numbers[-2:]      # [4, 5]
reversed_list = numbers[::-1] # [5, 4, 3, 2, 1]

List Comprehensions

Replace loops with comprehensions for cleaner code:

# Traditional loop
squares = []
for n in numbers:
    squares.append(n ** 2)

# List comprehension
squares = [n ** 2 for n in numbers]

Filtering with Comprehensions

# Filter high-temp models
models = ["gpt-4", "gpt-3.5-turbo", "claude-3", "llama-2"]
advanced_models = [m for m in models if "3" in m or "4" in m]

Nested Comprehensions

For AI data processing:

# Convert list of texts to list of token counts (simulated)
texts = ["hello", "world", "machine learning"]
token_counts = [len(text) * 1.3 for text in texts]  # rough approximation

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Given temperatures = [0.0, 0.3, 0.5, 0.7, 0.9, 1.0], use a list comprehension to create a list of descriptions: "very low", "low", "medium", "medium-high", "high", "maximum" for each temperature.