Chapter 3: Introducing Lists
Lists store ordered collections. The most versatile data structure in Python.
Creating Lists
Square brackets, comma-separated:
bikes = ['trek', 'cannondale', 'specialized']
numbers = [1, 2, 3, 4, 5]
mixed = ['text', 42, 3.14, True]
empty = []
Accessing Elements
Zero-indexed. First element is [0]:
bikes = ['trek', 'cannondale', 'specialized']
bikes[0] # 'trek'
bikes[1] # 'cannondale'
bikes[2] # 'specialized'
Negative indices count from the end:
bikes[-1] # 'specialized' (last)
bikes[-2] # 'cannondale' (second to last)
Use list elements like any variable:
print(f"First bike: {bikes[0].title()}")
Modifying Lists
Lists are mutable - you can change them after creation.
Change an Element
bikes[0] = 'giant'
# ['giant', 'cannondale', 'specialized']
Add Elements
bikes = ['honda', 'yamaha']
bikes.append('suzuki') # add to end
# ['honda', 'yamaha', 'suzuki']
bikes.insert(0, 'ducati') # insert at index
# ['ducati', 'honda', 'yamaha', 'suzuki']
Building lists dynamically:
servers = []
servers.append('web-01')
servers.append('web-02')
servers.append('db-01')
Remove Elements
Three ways, depending on what you need:
bikes = ['ducati', 'honda', 'yamaha', 'suzuki']
# By index - when you know position
del bikes[0]
# ['honda', 'yamaha', 'suzuki']
# By index - when you need the value
last = bikes.pop() # removes and returns last
# last = 'suzuki', bikes = ['honda', 'yamaha']
first = bikes.pop(0) # removes and returns index 0
# first = 'honda', bikes = ['yamaha']
# By value - when you know what to remove
bikes = ['honda', 'yamaha', 'suzuki']
bikes.remove('yamaha')
# ['honda', 'suzuki']
remove() only deletes the first occurrence. Use a loop for duplicates.
|
Organizing Lists
Permanent Sort
cars = ['bmw', 'audi', 'toyota']
cars.sort() # alphabetical
# ['audi', 'bmw', 'toyota']
cars.sort(reverse=True) # reverse alphabetical
# ['toyota', 'bmw', 'audi']
Temporary Sort
sorted() returns a new list, original unchanged:
cars = ['bmw', 'audi', 'toyota']
print(sorted(cars)) # ['audi', 'bmw', 'toyota']
print(cars) # ['bmw', 'audi', 'toyota'] - unchanged
Reverse Order
cars = ['bmw', 'audi', 'toyota']
cars.reverse()
# ['toyota', 'audi', 'bmw']
Not alphabetical - just reverses current order.
Length
len(cars) # 3
Index Errors
Accessing an index that doesn’t exist:
bikes = ['honda', 'yamaha', 'suzuki']
print(bikes[3]) # IndexError!
IndexError: list index out of range
Three items means indices 0, 1, 2. Index 3 doesn’t exist.
Safe access patterns:
# Use -1 for last item (always works)
bikes[-1]
# Check length first
if len(bikes) > 3:
print(bikes[3])
# Empty list check
if bikes: # truthy if not empty
print(bikes[-1])
Quick Reference
| Operation | Code |
|---|---|
Create |
|
Access |
|
Modify |
|
Append |
|
Insert |
|
Delete by index |
|
Pop (get + remove) |
|
Remove by value |
|
Sort permanent |
|
Sort temporary |
|
Reverse |
|
Length |
|
Exercises
3-1. Names
Store 3 names in a list. Print each using index access.
3-2. Greetings
Using your names list, print a personalized greeting for each.
3-3. Guest List
Create a dinner guest list. Print invitations. Then:
- One guest can’t come - replace them
- Found a bigger table - add 3 more guests (beginning, middle, end)
- Table cancelled - use pop() to remove all but 2, apologizing to each
3-4. Sorting
Create a list of places to visit.
- Print original order
- Print with sorted() (alphabetical)
- Prove original is unchanged
- Print with sorted(reverse=True)
- Use reverse() to flip it
- Use sort() to sort permanently
3-5. Index Error
Intentionally cause an IndexError. Then fix it.
Summary
-
Lists are ordered, mutable collections
-
Zero-indexed, negative indices count from end
-
append(),insert()to add;del,pop(),remove()to delete -
sort()is permanent,sorted()is temporary -
IndexErrormeans you’re accessing beyond the list bounds
Next: Looping through lists.