By the end of this lesson, you will be able to create Python lists, access elements using indexing and slicing, and modify them using common built-in methods.
What it is
A list in Python is an ordered, mutable collection of items. Unlike arrays in some other languages, Python lists can hold mixed data types (integers, strings, objects) within the same structure. The mental model is a numbered sequence of boxes where each box holds one item. Key related terms include index (the position number), slicing (extracting a sub-list), and iteration (looping through items).
Why it matters
- Data Aggregation: Lists are the primary way to store collections of similar or related data, such as user inputs or database records.
- Flexibility: Because they are mutable, you can add, remove, or change items dynamically during program execution.
- Interoperability: Most Python libraries and functions expect lists as input for processing batches of data.
- Simplicity: They provide intuitive syntax for accessing specific elements without complex pointer arithmetic.
Syntax or steps
Lists are defined by enclosing comma-separated values in square brackets []. Accessing elements uses zero-based indexing inside square brackets. Slicing uses the format list[start:stop:step], where start is inclusive and stop is exclusive.
Example
# Creating a list with mixed types
fruits = ["apple", "banana", "cherry", 42]
# Indexing: Accessing the first element
first_fruit = fruits[0]
print(first_fruit) # Output: apple
# Negative Indexing: Accessing the last element
last_item = fruits[-1]
print(last_item) # Output: 42
# Slicing: Getting a subset (indices 1 up to but not including 3)
middle_fruits = fruits[1:3]
print(middle_fruits) # Output: ['banana', 'cherry']
# Mutating: Adding and removing items
fruits.append("date") # Adds to end
fruits.remove("banana") # Removes first occurrence
print(fruits) # Output: ['apple', 'cherry', 42, 'date']
In this example, fruits[0] retrieves the item at index 0. fruits[-1] uses negative indexing to grab the last item. The slice [1:3] returns a new list containing items from index 1 and 2. Finally, .append() modifies the original list in place by adding an item, while .remove() deletes a specific value.
Common mistakes
- IndexError: Trying to access an index that does not exist (e.g.,
my_list[10]on a list of length 5). Always checklen(my_list)if unsure. - Confusing Assignment vs. Mutation: Using
=replaces the entire list object, while methods like.append()modify the existing object. Be careful when passing lists to functions; changes inside the function affect the original list. - Modifying While Iterating: Removing items from a list while looping over it can cause skipped elements or errors. Instead, iterate over a copy (
for item in my_list[:]:) or use list comprehensions to filter. - Assuming Homogeneity: Remember that lists can contain different types. Operations expecting only numbers (like summing) will fail if strings are present.
When to use it
Use lists when you need an ordered collection that may change size or content. Compare them with tuples and sets below.
| Structure | Mutability | Order | Duplicates | Best For |
|---|---|---|---|---|
| List | Mutable | Ordered | Allowed | Collections that change frequently |
| Tuple | Immutable | Ordered | Allowed | Fixed records (e.g., coordinates) |
| Set | Mutable | Unordered | No Duplicates | Unique items and fast lookups |
Practice
Guided Exercise: Create a list of numbers [1, 2, 3, 4, 5]. Use slicing to extract the middle three numbers. Then, append 6 to the end and print the final list.
Hint: The middle three indices are 1, 2, and 3. Slice with [1:4].
Challenge: Write a loop that prints every second item from the list ["a", "b", "c", "d", "e"] using step slicing.
Expected Output: a c e
Quick check
Question: What is the output of print([1, 2, 3][1])?
Answer: 2. The index 1 refers to the second element in the list.
Summary
Python lists are versatile, ordered, and mutable containers essential for managing dynamic data. Mastering indexing, slicing, and methods like append allows you to manipulate data efficiently. Choose lists over tuples or sets when your data requires order and frequent modification.