Collections are fundamental data structures in Python that allow you to store multiple values in a single variable. This chapter covers two essential collection types:
Mutable, ordered sequences
[1, 2, 3]Immutable, ordered sequences
(1, 2, 3)Learn how to create lists and tuples, access elements using indexes, and slice sequences.
Master append(), extend(), insert(), remove(), pop(), sort(), and reverse().
Build lists efficiently using list comprehension syntax.
Explore enumerate(), zip(), and shallow vs deep copying.
# Quick Examples
# Creating a list
fruits = ['apple', 'banana', 'cherry']
# Creating a tuple
coordinates = (10, 20)
# List comprehension
squares = [x**2 for x in range(5)]
# Tuple unpacking
x, y = coordinates
Visualize how lists work with indexing and slicing operations.
# Indexing Examples
my_list = [10, 20, 30, 40, 50]
my_list[0] # 10 (first element)
my_list[-1] # 50 (last element)
my_list[2] # 30 (third element)
# Slicing Examples
my_list[1:4] # [20, 30, 40]
my_list[:3] # [10, 20, 30] (first 3)
my_list[2:] # [30, 40, 50] (from index 2 onwards)
my_list[::2] # [10, 30, 50] (every 2nd element)
Experiment with list methods and see the results in real-time.
Adds an item to the end of the list.
lst.append(5)
Adds all items from another iterable.
lst.extend([4, 5])
Inserts item at the specified index.
lst.insert(0, 'x')
Removes the first occurrence of item.
lst.remove('x')
Removes and returns item at index (default: -1).
item = lst.pop()
Sorts the list in place.
lst.sort()
Reverses the list in place.
lst.reverse()
Removes all items from the list.
lst.clear()
Build list comprehensions visually and understand their structure.
# Basic comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# Transform strings
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
# ['ALICE', 'BOB', 'CHARLIE']
# Nested comprehension
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] |
(1, 2, 3) |
| Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
| Methods | Many (append, remove, etc.) | Few (count, index only) |
| Performance | Slower | Faster |
| Memory | More memory | Less memory |
| Use Case | When data changes | When data is constant |
# Creating tuples
point = (10, 20)
singleton = (42,) # Note the comma!
empty = ()
# Tuple unpacking
x, y = point # x=10, y=20
# Extended unpacking
first, *middle, last = (1, 2, 3, 4, 5)
# first=1, middle=[2,3,4], last=5
# Tuples as dictionary keys (lists can't do this!)
locations = {}
locations[(0, 0)] = 'origin'
locations[(1, 2)] = 'point A'
# Returning multiple values from a function
def get_coordinates():
return (10, 20) # Returns a tuple
x, y = get_coordinates()
# enumerate() gives you index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
# Start from different index
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}") # 1: apple, 2: banana, ...
# zip() combines multiple iterables
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['NYC', 'LA', 'Chicago']
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}")
# Create dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}
# Shallow copy - copies references
original = [1, 2, [3, 4]]
shallow = original.copy() # or original[:]
shallow[0] = 100
shallow[2][0] = 999
# original = [1, 2, [999, 4]] <- nested list affected!
# shallow = [100, 2, [999, 4]]
# Deep copy - copies everything recursively
import copy
original = [1, 2, [3, 4]]
deep = copy.deepcopy(original)
deep[0] = 100
deep[2][0] = 999
# original = [1, 2, [3, 4]] <- unchanged!
# deep = [100, 2, [999, 4]]
max_val = max(my_list)
Returns the largest element
min_val = min(my_list)
Returns the smallest element
total = sum(my_list)
Adds all numeric elements
if item in my_list:
Check if item exists
size = len(my_list)
Get number of elements
all([True, True])
Check if all/any are True
Test your understanding of lists and tuples!