Chapter 7: Lists: Storing Collections π
So far, youβve been storing single values in variables β one name, one score, one temperature. But what if you need to store multiple related items? A shopping list, a collection of high scores, or a playlist of songs? Thatβs where lists come in!
Lists are one of Pythonβs most useful data structures. They let you organize multiple values under a single name, making your code cleaner and more powerful. By the end of this chapter, youβll be able to store, access, modify, and process collections of data with ease.
Introduction to Lists π―
A list is a collection of items stored in a single variable. Think of it like a container that holds multiple values in a specific order.
Creating Lists
To create a list, use square brackets [] with items separated by commas:
# A list of numbers
scores = [85, 92, 78, 95, 88]
# A list of strings
fruits = ["apple", "banana", "orange", "grape"]
# A list with mixed types (numbers and strings)
mixed = [42, "hello", 3.14, "world"]
# An empty list
empty_list = []
Each item in a list is called an element. Lists can contain any type of data β numbers, strings, booleans, even other lists!
Why Use Lists?
Without lists, storing multiple related values would be messy:
# Without lists - messy and hard to manage
score1 = 85
score2 = 92
score3 = 78
score4 = 95
score5 = 88
With lists, itβs clean and organized:
# With lists - clean and easy to work with
scores = [85, 92, 78, 95, 88]
Displaying Lists
You can print an entire list at once:
colors = ["red", "green", "blue"]
print(colors) # Shows: ['red', 'green', 'blue']
Or use a loop to display each item on its own line (weβll explore this more later):
colors = ["red", "green", "blue"]
for color in colors:
print(color)
# Output:
# red
# green
# blue
Accessing List Items π
Lists maintain the order in which you add items. Each item has a position called an index. Python uses zero-based indexing, which means the first item is at index 0, the second at index 1, and so on.
Using Index Numbers
To access an item, use square brackets with the index number:
fruits = ["apple", "banana", "orange", "grape"]
print(fruits[0]) # Shows: apple
print(fruits[1]) # Shows: banana
print(fruits[2]) # Shows: orange
print(fruits[3]) # Shows: grape
Visual representation:
Index: 0 1 2 3
ββββββββββ¬βββββββββ¬βββββββββ¬βββββββββ
fruits: β apple β banana β orange β grape β
ββββββββββ΄βββββββββ΄βββββββββ΄βββββββββ
Negative Indexing
Python also supports negative indices, which count from the end of the list:
fruits = ["apple", "banana", "orange", "grape"]
print(fruits[-1]) # Shows: grape (last item)
print(fruits[-2]) # Shows: orange (second to last)
print(fruits[-3]) # Shows: banana
print(fruits[-4]) # Shows: apple (same as fruits[0])
Negative indexing is handy when you want the last item but donβt know the listβs length.
Index Out of Range Error
If you try to access an index that doesnβt exist, Python raises an error:
fruits = ["apple", "banana", "orange"]
print(fruits[5]) # ERROR: IndexError: list index out of range
There are only 3 items (indices 0, 1, 2), so index 5 doesnβt exist.
Using List Items
Once you access an item, you can use it like any other variable:
prices = [19.99, 24.50, 15.75, 32.00]
first_price = prices[0]
second_price = prices[1]
total = first_price + second_price
print(f"Total: ${total}") # Shows: Total: $44.49
You can also use list items in f-strings and other operations:
names = ["Alice", "Bob", "Charlie"]
print(f"Welcome, {names[0]}!") # Shows: Welcome, Alice!
print(f"The winner is {names[0]}, runner-up is {names[1]}")
Modifying Lists βοΈ
Unlike strings (which are immutable), lists can be changed after creation. You can update items, add new ones, or remove existing ones.
Changing List Items
To change an item, assign a new value to a specific index:
fruits = ["apple", "banana", "orange"]
print(fruits) # Shows: ['apple', 'banana', 'orange']
fruits[1] = "mango"
print(fruits) # Shows: ['apple', 'mango', 'orange']
You can update multiple items:
scores = [75, 82, 90, 68]
print(scores) # Shows: [75, 82, 90, 68]
scores[0] = 85 # Update first score
scores[3] = 78 # Update last score
print(scores) # Shows: [85, 82, 90, 78]
Adding Items with .append()
The .append() method adds an item to the end of the list:
games = ["Minecraft", "Roblox"]
print(games) # Shows: ['Minecraft', 'Roblox']
games.append("Fortnite")
print(games) # Shows: ['Minecraft', 'Roblox', 'Fortnite']
games.append("Among Us")
print(games) # Shows: ['Minecraft', 'Roblox', 'Fortnite', 'Among Us']
This is perfect for building lists dynamically:
shopping_list = []
shopping_list.append("milk")
shopping_list.append("bread")
shopping_list.append("eggs")
print(shopping_list) # Shows: ['milk', 'bread', 'eggs']
Adding Items with .insert()
While .append() adds to the end, .insert() adds an item at a specific position:
colors = ["red", "blue", "green"]
colors.insert(1, "yellow") # Insert at index 1
print(colors) # Shows: ['red', 'yellow', 'blue', 'green']
The syntax is .insert(index, item) β the new item goes at the specified index, and existing items shift to the right.
Practical Example: Building a Playlist
playlist = []
print("=== Music Playlist Builder ===\n")
# Add songs
playlist.append("Bohemian Rhapsody")
playlist.append("Stairway to Heaven")
playlist.append("Hotel California")
print("Current playlist:")
for i in range(len(playlist)):
print(f"{i + 1}. {playlist[i]}")
# Update a song
playlist[1] = "Imagine"
print("\nUpdated playlist:")
for i in range(len(playlist)):
print(f"{i + 1}. {playlist[i]}")
Removing from Lists ποΈ
Python provides several ways to remove items from lists, each useful in different situations.
Removing with .pop()
The .pop() method removes and returns an item. By default, it removes the last item:
fruits = ["apple", "banana", "orange", "grape"]
removed = fruits.pop()
print(f"Removed: {removed}") # Shows: Removed: grape
print(fruits) # Shows: ['apple', 'banana', 'orange']
You can also specify which index to remove:
fruits = ["apple", "banana", "orange", "grape"]
removed = fruits.pop(1) # Remove item at index 1
print(f"Removed: {removed}") # Shows: Removed: banana
print(fruits) # Shows: ['apple', 'orange', 'grape']
This is like taking an item out of the list and keeping it for later use.
Removing with .remove()
The .remove() method removes the first occurrence of a specific value:
colors = ["red", "blue", "green", "blue"]
colors.remove("blue") # Removes the first 'blue'
print(colors) # Shows: ['red', 'green', 'blue']
If the value isnβt in the list, youβll get an error:
colors = ["red", "green", "blue"]
colors.remove("yellow") # ERROR: ValueError: 'yellow' is not in list
Using del Statement
The del statement removes an item at a specific index (without returning it):
numbers = [10, 20, 30, 40, 50]
del numbers[2] # Delete item at index 2
print(numbers) # Shows: [10, 20, 40, 50]
You can also delete multiple items using slicing (advanced topic):
numbers = [10, 20, 30, 40, 50]
del numbers[1:3] # Delete items from index 1 to 2 (not including 3)
print(numbers) # Shows: [10, 40, 50]
Clearing the Entire List
To remove all items but keep the list, use .clear():
tasks = ["task1", "task2", "task3"]
tasks.clear()
print(tasks) # Shows: []
When to Use Each Method
.pop()β When you need to remove an item and use its value.remove()β When you know the value but not the indexdelβ When you know the index and donβt need the value.clear()β When you want to empty the entire list
Looping Through Lists π
One of the most powerful features of lists is the ability to process each item automatically using loops. This combination is incredibly common in programming.
The for Loop with Lists
The most natural way to iterate through a list is with a for loop:
fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
print(f"I like {fruit}s!")
Output:
I like apples!
I like bananas!
I like oranges!
I like grapes!
This reads naturally: βFor each fruit in fruits, do thisβ¦β
Accessing Index While Looping
Sometimes you need both the item and its index. Use enumerate():
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Color {index}: {color}")
Output:
Color 0: red
Color 1: green
Color 2: blue
If you want indices to start at 1 instead of 0:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors, start=1):
print(f"Color {index}: {color}")
Output:
Color 1: red
Color 2: green
Color 3: blue
Processing Lists with Loops
Example 1: Calculate total
prices = [19.99, 24.50, 15.75, 32.00, 8.99]
total = 0
for price in prices:
total += price
print(f"Total: ${total:.2f}") # Shows: Total: $101.23
Example 2: Find the maximum
scores = [85, 92, 78, 95, 88]
highest = scores[0] # Start with first score
for score in scores:
if score > highest:
highest = score
print(f"Highest score: {highest}") # Shows: Highest score: 95
Example 3: Filter items
numbers = [5, 12, 8, 21, 3, 15, 7]
print("Even numbers:")
for num in numbers:
if num % 2 == 0:
print(num)
# Output: 12, 8
Example 4: Transform items
names = ["alice", "bob", "charlie"]
print("Formatted names:")
for name in names:
formatted = name.title()
print(formatted)
# Output: Alice, Bob, Charlie
Building New Lists from Existing Ones
# Double all numbers
original = [1, 2, 3, 4, 5]
doubled = []
for num in original:
doubled.append(num * 2)
print(doubled) # Shows: [2, 4, 6, 8, 10]
List Helpers π οΈ
Python provides several useful functions and operators for working with lists.
The len() Function
Get the number of items in a list:
fruits = ["apple", "banana", "orange"]
count = len(fruits)
print(f"There are {count} fruits") # Shows: There are 3 fruits
This is essential for loops and boundary checking:
scores = [85, 92, 78, 95, 88]
for i in range(len(scores)):
print(f"Score {i + 1}: {scores[i]}")
The in Operator
Check if an item exists in a list:
fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
print("We have bananas!") # This prints
if "mango" in fruits:
print("We have mangos!") # This doesn't print
The not in operator checks if an item is absent:
shopping_list = ["milk", "bread", "eggs"]
if "butter" not in shopping_list:
print("Don't forget to buy butter!")
The .sort() Method
Sort a list in place (modifies the original list):
numbers = [42, 15, 8, 23, 4]
numbers.sort()
print(numbers) # Shows: [4, 8, 15, 23, 42]
For strings, sorting is alphabetical:
names = ["Charlie", "Alice", "Bob"]
names.sort()
print(names) # Shows: ['Alice', 'Bob', 'Charlie']
Sort in reverse (descending) order:
numbers = [42, 15, 8, 23, 4]
numbers.sort(reverse=True)
print(numbers) # Shows: [42, 23, 15, 8, 4]
The sorted() Function
Create a new sorted list without modifying the original:
original = [42, 15, 8, 23, 4]
sorted_list = sorted(original)
print(original) # Shows: [42, 15, 8, 23, 4]
print(sorted_list) # Shows: [4, 8, 15, 23, 42]
The .reverse() Method
Reverse the order of items:
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Shows: [5, 4, 3, 2, 1]
The .count() Method
Count how many times a value appears:
numbers = [1, 2, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(f"The number 2 appears {count} times") # Shows: 4 times
The .index() Method
Find the index of the first occurrence of a value:
fruits = ["apple", "banana", "orange", "banana"]
position = fruits.index("banana")
print(f"First banana is at index {position}") # Shows: index 1
Finding Min and Max
Use built-in functions:
scores = [85, 92, 78, 95, 88]
highest = max(scores)
lowest = min(scores)
total = sum(scores)
average = total / len(scores)
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
print(f"Average: {average:.1f}")
Quick Recap π―
Youβve learned how to work with lists in Python:
- Create lists with square brackets
[] - Access items using index numbers (starting at 0)
- Modify items by assigning new values to indices
- Add items with
.append()and.insert() - Remove items with
.pop(),.remove(), anddel - Loop through lists with
forloops - Use helpers like
len(),in,.sort(), and more
Lists are essential for organizing and managing collections of data!
Hands-On Mini Project: To-Do List Manager π
Letβs build a functional to-do list application that puts all your list skills to work!
Your Mission
Create an interactive to-do list manager where users can:
- Add new tasks
- View all tasks
- Mark tasks as complete (remove them)
- Clear all tasks
- Exit the program
Example Solution
print("=" * 50)
print(" TO-DO LIST MANAGER")
print("=" * 50)
print()
# Initialize empty to-do list
todo_list = []
# Main program loop
running = True
while running:
# Display menu
print("\nWhat would you like to do?")
print("1. View tasks")
print("2. Add a task")
print("3. Complete a task")
print("4. Clear all tasks")
print("5. Exit")
choice = input("\nEnter your choice (1-5): ")
print()
# View tasks
if choice == "1":
if len(todo_list) == 0:
print("Your to-do list is empty! π")
else:
print("=" * 50)
print("YOUR TO-DO LIST:")
print("=" * 50)
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
print("=" * 50)
# Add a task
elif choice == "2":
task = input("Enter the new task: ")
todo_list.append(task)
print(f"β Added: '{task}'")
print(f"You now have {len(todo_list)} task(s).")
# Complete a task
elif choice == "3":
if len(todo_list) == 0:
print("No tasks to complete!")
else:
print("Current tasks:")
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
task_num = int(input("\nEnter task number to complete: "))
if task_num < 1 or task_num > len(todo_list):
print("Invalid task number!")
else:
completed = todo_list.pop(task_num - 1)
print(f"β Completed: '{completed}'")
print(f"You have {len(todo_list)} task(s) remaining.")
# Clear all tasks
elif choice == "4":
if len(todo_list) == 0:
print("Your list is already empty!")
else:
confirm = input(f"Are you sure you want to delete all {len(todo_list)} tasks? (yes/no): ")
if confirm.lower() == "yes":
todo_list.clear()
print("β All tasks cleared!")
else:
print("Cancelled.")
# Exit
elif choice == "5":
if len(todo_list) > 0:
print("You still have tasks remaining:")
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
print()
print("Thanks for using To-Do List Manager!")
print("Goodbye! π")
running = False
# Invalid choice
else:
print("Invalid choice. Please enter 1-5.")
print()
print("=" * 50)
Challenge Yourself
Enhance your to-do list with these features:
- Priority levels β Add HIGH, MEDIUM, LOW priority to tasks
- Due dates β Let users add deadlines to tasks
- Save and load β Make tasks persist between runs (using file I/O)
- Task categories β Organize tasks by category (work, personal, school)
- Search tasks β Find tasks containing specific keywords
- Edit tasks β Modify existing task descriptions
- Task statistics β Show total tasks added, completed, etc.
Tips for Building
- Use
len()to check if the list is empty before accessing items - Validate user input to prevent index errors
- Give clear feedback after each action
- Test edge cases (empty list, invalid indices, etc.)
- Use
enumerate()to display numbered lists
Whatβs Next?
In the next chapter, youβll learn about dictionaries β a powerful way to store data using key-value pairs. While lists use numeric indices, dictionaries let you use meaningful labels to organize information!
Get ready to take your data organization skills to the next level!
Excellent work! Lists are fundamental to Python programming, and youβve mastered them!