Introduction to Lists and Dictionaries
Chapter 1: Introduction to Lists and Dictionaries
Welcome to Lesson 6! In the previous lessons, you learned about variables, conditions, loops, and functions. Now, it's time to learn about two of the most powerful and commonly used data structures in Python: lists and dictionaries. These structures allow you to store and organize multiple pieces of data efficiently. By the end of this chapter, you will be able to create, access, modify, and use lists and dictionaries in your programs.
Why Do We Need Lists and Dictionaries?
Imagine you are building a simple task manager. You need to store a list of tasks, each with a title, description, and status. Using individual variables for each task would be messy and inefficient. Lists and dictionaries solve this problem by allowing you to group related data together. Lists are perfect for ordered collections of items, while dictionaries are ideal for storing key-value pairs, like a task's title and its status.
What Are Lists?
A list is an ordered, mutable collection of items. You can store any type of data in a list, including numbers, strings, or even other lists. Lists are defined using square brackets [] and items are separated by commas.
Creating a List
# An empty list
empty_list = []
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A mixed list
mixed = [1, "hello", 3.14, True]
Accessing List Items
You can access individual items in a list using their index. Python uses zero-based indexing, meaning the first item is at index 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (negative index starts from the end)
Modifying a List
Lists are mutable, so you can change, add, or remove items after creation.
# Change an item
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
# Add an item to the end
fruits.append("date")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
# Insert an item at a specific position
fruits.insert(1, "banana")
print(fruits) # Output: ['apple', 'banana', 'blueberry', 'cherry', 'date']
# Remove an item by value
fruits.remove("banana")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
# Remove an item by index
removed_item = fruits.pop(2)
print(removed_item) # Output: cherry
print(fruits) # Output: ['apple', 'blueberry', 'date']
Looping Through a List
You can use a for loop to iterate over all items in a list.
for fruit in fruits:
print(f"I like {fruit}")
What Are Dictionaries?
A dictionary is an unordered, mutable collection of key-value pairs. Each key must be unique and immutable (like a string, number, or tuple), while values can be any data type. Dictionaries are defined using curly braces {}.
Creating a Dictionary
# An empty dictionary
empty_dict = {}
# A dictionary with string keys
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# A dictionary with mixed keys
mixed_dict = {
"name": "Bob",
1: "one",
(2, 3): "tuple key"
}
Accessing Dictionary Values
You access values by their keys using square brackets or the get() method.
print(person["name"]) # Output: Alice
print(person.get("age")) # Output: 30
# Using get() avoids KeyError if the key doesn't exist
print(person.get("country", "Not found")) # Output: Not found
Modifying a Dictionary
You can add, change, or remove key-value pairs.
# Add a new key-value pair
person["email"] = "alice@example.com"
print(person)
# Change an existing value
person["age"] = 31
print(person)
# Remove a key-value pair
del person["city"]
print(person)
# Remove and return a value
age = person.pop("age")
print(age) # Output: 31
print(person) # Output: {'name': 'Alice', 'email': 'alice@example.com'}
Looping Through a Dictionary
You can loop through keys, values, or both.
# Loop through keys
for key in person:
print(key)
# Loop through values
for value in person.values():
print(value)
# Loop through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Practical Example: A Simple Task Manager
Let's combine lists and dictionaries to create a simple task manager. We'll store tasks in a list, where each task is a dictionary.
# List of tasks
tasks = []
# Function to add a task
def add_task(title, description):
task = {
"title": title,
"description": description,
"completed": False
}
tasks.append(task)
print(f"Task '{title}' added.")
# Function to list all tasks
def list_tasks():
if not tasks:
print("No tasks yet.")
return
for i, task in enumerate(tasks, start=1):
status = "✓" if task["completed"] else "✗"
print(f"{i}. [{status}] {task['title']}: {task['description']}")
# Function to mark a task as completed
def complete_task(index):
if 0 <= index < len(tasks):
tasks[index]["completed"] = True
print(f"Task '{tasks[index]['title']}' marked as completed.")
else:
print("Invalid task index.")
# Example usage
add_task("Learn Python", "Study lists and dictionaries")
add_task("Build API", "Create a REST API with FastAPI")
list_tasks()
complete_task(0)
list_tasks()
- IndexError: Accessing an index that doesn't exist in a list. Always check the list length before accessing an index.
- KeyError: Accessing a key that doesn't exist in a dictionary. Use the
get()method to avoid this. - Mutable vs Immutable: Remember that lists and dictionaries are mutable, but keys in dictionaries must be immutable (e.g., strings, numbers, tuples).
- Copying: Be careful when copying lists or dictionaries. Use
copy()ordeepcopy()to create independent copies.
Practice Task
Create a Python script that does the following:
- Create a list of dictionaries, where each dictionary represents a student with keys:
name,age, andgrades(a list of numbers). - Write a function that calculates and prints the average grade for each student.
- Write a function that finds and prints the name of the student with the highest average grade.
Test your script with at least three students. This exercise will help you practice combining lists and dictionaries in a real-world scenario.
Loading ratings...