A neural network might process a batch of 10,000 images at once. A web scraper might extract 500 URLs from a webpage. To manage these collections of data, you need an ordered, dynamic data structure. In Python, the List is the fundamental building block for all sequence data.
1Declaring and Accessing Data
Python lists are defined using square brackets [], with items separated by commas. Unlike arrays in stricter languages (like C or Java), Python lists are completely heterogeneous—meaning you can mix strings, integers, floats, and even other lists inside a single list.
Lists are "ordered", meaning Python remembers the exact sequence you put the items in. You retrieve data using Zero-Based Indexing. The very first item is at index 0. Python also supports negative indexing, which is a massive quality-of-life feature: index -1 always grabs the very last item in the list, -2 grabs the second to last, and so on.
# A mixed-type list
model_config = ["GPT-4", 0.01, 1024]
# Zero-based indexing
name = model_config[0]
print(f"Model Name: {name}")
# Negative indexing
max_tokens = model_config[-1]
print(f"Max Tokens (Last Item): {max_tokens}")Max Tokens (Last Item): 1024
2Slicing Sequences
When working with time-series data or batching AI inputs, you rarely want just one item; you want a *chunk* of items. Python provides 'Slicing' for this. The syntax is list[start:stop].
Crucially, slicing is inclusive of the start index, but exclusive of the stop index. If you request [1:4], Python will return indices 1, 2, and 3. It stops exactly *before* it hits index 4. You can also omit numbers: [:3] grabs everything from the absolute beginning up to index 3, and [2:] grabs everything from index 2 to the absolute end.
sensors = [12.5, 13.1, 14.0, 13.8, 12.9]
# Indices 1 and 2 (3 is excluded)
mid_data = sensors[1:3]
print(f"Middle Slice: {mid_data}")
# Everything from index 2 to the end
end_data = sensors[2:]
print(f"End Slice: {end_data}")End Slice: [14.0, 13.8, 12.9]
3In-Place Mutation
Unlike strings or tuples, Lists are "Mutable". This means their internal data can be changed, resized, and overwritten after the list has been created, without needing to create a completely new list in memory.
The .append(item) method is the most common mutation. It tacks a new element onto the absolute end of the list. Because mutation happens 'in-place', the method .append() actually returns None. It modifies the existing list object in memory. You can also reassign specific indices directly, e.g., my_list[0] = "New Value".
queue = ["Task 1", "Task 2"]
# Add to the end (in-place)
queue.append("Task 3")
# Overwrite an existing index
queue[0] = "Task 1 (COMPLETED)"
print(queue)