This chapter introduces the first two fundamental collection data types in Python: Lists (mutable) and Tuples (immutable). These structures are essential for organizing multiple pieces of data efficiently.
1. Lists (list)
A List is an ordered, changeable (mutable) collection of data. Lists are the most versatile and commonly used sequence type in Python.
A. Creating and Accessing Lists
- Lists are defined using square brackets
[]. - Lists can hold items of different data types.
- Elements are accessed using indexing (starting at $0$), just like strings.
my_list = ["apple", 10, True, 3.14]
print(my_list[0]) # Output: apple
print(my_list[-1]) # Output: 3.14 (Accessing the last element)
B. Mutability: Modifying Lists
Since lists are mutable, you can change their contents after creation.
| Method | Description | Example |
| Indexing | Change a specific element. | my_list[1] = 12 |
append() | Adds a single element to the end of the list. | my_list.append("orange") |
insert() | Adds an element at a specified index. | my_list.insert(1, "banana") |
remove() | Removes the first occurrence of a specified value. | my_list.remove(10) |
pop() | Removes and returns the item at a specified index (or the last item if no index is given). | item = my_list.pop() |
shopping_list = ["bread", "milk", "eggs"]
shopping_list.append("cheese") # Add to end
shopping_list.remove("milk") # Remove milk
print(shopping_list) # Output: ['bread', 'eggs', 'cheese']
C. List Slicing
Slicing works identically to string slicing (P1.3) to extract a portion (a sublist) from the list.
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # Elements from index 1 up to (but not including) 4
print(subset) # Output: [2, 3, 4]
D. List Comprehensions (Intermediate Technique)
List comprehensions provide a concise way to create lists based on existing sequences.
Syntax: [expression for item in iterable if condition]
# Create a list of squares for even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # Output: [0, 4, 16, 36, 64]
2. Tuples (tuple)
A Tuple is an ordered, unchangeable (immutable) collection of data. Tuples are generally faster than lists and are used when you need to ensure the data cannot be modified.
A. Creating and Accessing Tuples
- Tuples are defined using parentheses
()(though often the parentheses are optional). - Accessing elements is done via indexing, identical to lists.
my_tuple = ("red", "green", "blue")
single_item_tuple = (5,) # MUST include a trailing comma for a single-item tuple
print(my_tuple[0]) # Output: red
B. Immutability
You cannot change, add, or remove elements after a tuple is created. Attempting to do so will result in a TypeError.
coordinates = (10, 20)
# coordinates[0] = 5 # ERROR: 'tuple' object does not support item assignment
3. Essential Built-in Iteration Functions
These functions are often used when looping over lists or other sequences.
| Function | Purpose | Example |
len() | Returns the number of items in the list/tuple. | len(my_list) |
enumerate() | Returns both the index and the value during iteration. | for i, val in enumerate(my_list): |
zip() | Combines two or more iterables, pairing up elements from each. | for a, b in zip(list_a, list_b): |
names = ["A", "B", "C"]
# Using enumerate to get index and value
for index, name in enumerate(names):
print(f"{index}: {name}")
