- Understand what lists are and why they're essential
- Create, access, and modify list elements
- Use common list methods and operations
- Work with list slicing and iteration
Lists: Your First Collection
Imagine you're planning a party and need to track your guest list. You could create a variable for each guest: guest1 = "Alice", guest2 = "Bob", guest3 = "Carol"... But what if you have 50 guests? What if guests get added or removed? This approach quickly becomes unmanageable.
This is exactly why lists exist. A list is a single container that can hold multiple items, like a shopping list, a playlist, or a guest list. It's one of Python's most versatile and commonly used data structures – you'll use lists in almost every program you write.
What is a List?
A list is an ordered, mutable collection of items. Let's break that down:
List Characteristics
ORDERED: Items stay in the order you put them
First in → First position
MUTABLE: You can change, add, or remove items
Lists can grow and shrink
INDEXED: Each item has a position number (starting at 0)
Access items by their index
FLEXIBLE: Can hold any type of data
Mix strings, numbers, even other lists!
Real-World Analogies
| Real-World | Python List |
|---|---|
| Shopping list | ["milk", "eggs", "bread"] |
| Music playlist | ["Song A", "Song B", "Song C"] |
| Student grades | [85, 92, 78, 95] |
| To-do items | ["Email boss", "Buy groceries", "Call mom"] |
| Lottery numbers | [7, 14, 21, 28, 35] |
Creating Lists
Basic List Creation
# Empty list - ready to fill later
empty_list = []
# List with initial values
fruits = ["apple", "banana", "cherry"]
# Numbers
scores = [85, 92, 78, 95, 88]
# Mixed types (Python allows this!)
mixed = ["Alice", 25, True, 3.14]
# List from other iterables
letters = list("Hello") # ['H', 'e', 'l', 'l', 'o']
Visual Representation
List: fruits
Index: 0 1 2
Values: "apple" "banana""cherry"
Negative: -3 -2 -1
Index
fruits[0] → "apple"
fruits[2] → "cherry"
fruits[-1] → "cherry" (last item)
Accessing List Elements
Positive Indexing (From the Start)
Indexing starts at 0, not 1! This is one of the most important concepts:
colors = ["red", "green", "blue", "yellow"]
first = colors[0] # "red"
second = colors[1] # "green"
third = colors[2] # "blue"
fourth = colors[3] # "yellow"
# colors[4] would cause IndexError (out of range!)
Negative Indexing (From the End)
Python lets you count backwards from the end:
colors = ["red", "green", "blue", "yellow"]
last = colors[-1] # "yellow"
second_last = colors[-2] # "blue"
third_last = colors[-3] # "green"
Pro Tip: Use
[-1]when you need the last element but don't know the list length!
Why Does Indexing Start at 0?
Think of the index as an "offset" from the start:
- Index 0 = 0 steps from the beginning → first element
- Index 1 = 1 step from the beginning → second element
- And so on...
Slicing: Getting Multiple Elements
Slicing lets you extract a portion of a list.
Basic Slicing Syntax
list[start:stop:step]
- start: Where to begin (included)
- stop: Where to end (excluded)
- step: How many to skip (optional)
Slicing Examples
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 2 to 5 (5 not included)
numbers[2:5] # [2, 3, 4]
# From start to index 4
numbers[:4] # [0, 1, 2, 3]
# From index 6 to end
numbers[6:] # [6, 7, 8, 9]
# Every second element
numbers[::2] # [0, 2, 4, 6, 8]
# Reverse the list
numbers[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Last three elements
numbers[-3:] # [7, 8, 9]
Visual Guide to Slicing
Slicing Visualization
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
↑ ↑ ↑ ↑
Index: 0 2 6 9
numbers[2:6] → [2, 3, 4, 5]
←
start stop-1
Think of it as: "Start at 2, stop BEFORE 6"
Modifying Lists
Lists are mutable – you can change them after creation!
Changing Elements
fruits = ["apple", "banana", "cherry"]
# Change single element
fruits[1] = "blueberry"
print(fruits) # ["apple", "blueberry", "cherry"]
# Change multiple elements with slicing
fruits[0:2] = ["apricot", "blackberry"]
print(fruits) # ["apricot", "blackberry", "cherry"]
Adding Elements
fruits = ["apple", "banana"]
# append() - Add to the end
fruits.append("cherry")
print(fruits) # ["apple", "banana", "cherry"]
# insert() - Add at specific position
fruits.insert(1, "apricot")
print(fruits) # ["apple", "apricot", "banana", "cherry"]
# extend() - Add multiple items
fruits.extend(["date", "elderberry"])
print(fruits) # ["apple", "apricot", "banana", "cherry", "date", "elderberry"]
Removing Elements
fruits = ["apple", "banana", "cherry", "banana", "date"]
# remove() - Remove first occurrence of value
fruits.remove("banana")
print(fruits) # ["apple", "cherry", "banana", "date"]
# pop() - Remove and return item at index (default: last)
last = fruits.pop()
print(last) # "date"
print(fruits) # ["apple", "cherry", "banana"]
first = fruits.pop(0)
print(first) # "apple"
print(fruits) # ["cherry", "banana"]
# del - Delete by index or slice
del fruits[0]
print(fruits) # ["banana"]
# clear() - Remove all items
fruits.clear()
print(fruits) # []
Common List Operations
List Methods at a Glance
| Method | Description | Example |
|---|---|---|
append(x) |
Add x to end | [1,2].append(3) → [1,2,3] |
insert(i,x) |
Insert x at index i | [1,3].insert(1,2) → [1,2,3] |
extend(list) |
Add all items from list | [1].extend([2,3]) → [1,2,3] |
remove(x) |
Remove first x | [1,2,1].remove(1) → [2,1] |
pop(i) |
Remove & return at i | [1,2,3].pop(1) → 2 |
index(x) |
Find index of x | ['a','b'].index('b') → 1 |
count(x) |
Count occurrences | [1,1,2].count(1) → 2 |
sort() |
Sort in place | [3,1,2].sort() → [1,2,3] |
reverse() |
Reverse in place | [1,2,3].reverse() → [3,2,1] |
copy() |
Create shallow copy | [1,2].copy() → [1,2] |
Useful Built-in Functions
numbers = [4, 2, 9, 1, 7]
len(numbers) # 5 (number of items)
max(numbers) # 9 (largest)
min(numbers) # 1 (smallest)
sum(numbers) # 23 (total)
sorted(numbers) # [1, 2, 4, 7, 9] (returns NEW sorted list)
list(reversed(numbers)) # [7, 1, 9, 2, 4]
Iterating Through Lists
Simple Iteration
fruits = ["apple", "banana", "cherry"]
# Most common way
for fruit in fruits:
print(f"I like {fruit}!")
# Output:
# I like apple!
# I like banana!
# I like cherry!
With Index (enumerate)
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index + 1}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. cherry
Building New Lists
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]
Checking List Membership
fruits = ["apple", "banana", "cherry"]
# Check if item exists
print("banana" in fruits) # True
print("mango" in fruits) # False
# Check if item doesn't exist
print("mango" not in fruits) # True
# Use in conditions
if "apple" in fruits:
print("We have apples!")
Practical Example: Shopping Cart
# Shopping cart system
cart = []
print(" Shopping Cart System")
print("=" * 30)
# Add items
cart.append({"item": "Laptop", "price": 999.99})
cart.append({"item": "Mouse", "price": 29.99})
cart.append({"item": "Keyboard", "price": 79.99})
# Display cart
print("\nYour Cart:")
for i, product in enumerate(cart, 1):
print(f" {i}. {product['item']}: ${product['price']:.2f}")
# Calculate total
total = sum(item['price'] for item in cart)
print("-" * 30)
print(f"Total: ${total:.2f}")
# Remove an item
cart.pop(1) # Remove Mouse
print(f"\nAfter removing Mouse: {len(cart)} items left")
# Check if empty
if cart:
print("Cart has items!")
else:
print("Cart is empty!")
Common Pitfalls
1. Index Out of Range
fruits = ["apple", "banana"]
# fruits[5] # IndexError! List only has indices 0 and 1
2. Modifying While Iterating
# WRONG - Don't modify list while iterating
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
numbers.remove(n) # Dangerous!
# CORRECT - Create new list or iterate over copy
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0] # List comprehension
3. List Assignment vs Copy
# This creates a REFERENCE, not a copy!
original = [1, 2, 3]
reference = original
reference.append(4)
print(original) # [1, 2, 3, 4] - Original changed too!
# Use copy() for independent copy
original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original) # [1, 2, 3] - Original unchanged
Key Takeaways
Remember These Points
Lists are ordered, mutable collections: [1, 2, 3]
Indexing starts at 0, negative index starts from end
list[0] = first, list[-1] = last
Slicing: list[start:stop:step]
Stop is always excluded!
Add: append(), insert(), extend()
Remove: remove(), pop(), del, clear()
Check membership: "item" in list
Be careful with references vs copies!
What's Next?
You've mastered lists – Python's most versatile collection! But what if you need a collection that can't be changed? In the next lesson, we'll explore tuples – immutable sequences that are perfect for data that should stay constant.
