Hello! Welcome to your third lesson in the course.
In our last session, you learned how to use conditional statements (if, elif, else) to make your programs make decisions. This is a fundamental skill for creating dynamic and interactive applications.
So far, our programs have mostly worked with single pieces of data at a time—one number, one line of text. But to build your text analysis tool, you'll need to handle collections of data, like all the sentences in a paragraph or a list of words to check for. Today, we'll dive into two of Python's most powerful data structures for this purpose: lists and dictionaries. Mastering these will allow you to store, manage, and process structured data, a crucial step toward building your application.
Lists: Storing Ordered Collections
Imagine you have a shopping list. It's a collection of items, and the order might matter. A Python list works the same way: it's a variable that can hold multiple values in an ordered sequence.
Creating and Understanding Lists
You create a list by placing items inside square brackets [], separated by commas.
# A list of strings
programming_languages = ["Python", "JavaScript", "HTML", "CSS"]
# A list of integers
primes = [2, 3, 5, 7, 11]
# A list with mixed data types
mixed_list = ["Hello", 42, True]
The video below gives a great introduction to lists and how to create them. It also briefly mentions other collection types, but for now, our focus is just on lists.
Python lists, sets, and tuples explained 🍍
Watch this segment from Bro Code to see how lists are defined and used to store multiple values in a single variable.
Watch from the beginning up to 01:42. Pay attention to the square bracket [] syntax and the naming convention of using a plural name (e.g., fruits) for a list variable.
Accessing and Modifying List Items
Once you have a list, you'll want to work with the items inside it. You can access individual items using their index—their position in the list. In Python, indexing starts at 0.
fruits = ["apple", "orange", "banana", "coconut"]
# Access the first item (index 0)
first_fruit = fruits[0] # This will be "apple"
print(first_fruit)
# Access the third item (index 2)
third_fruit = fruits[2] # This will be "banana"
print(third_fruit)
Lists are mutable, which means you can change them after they are created. You can add new items, remove existing ones, or change an item at a specific index.
# Change an item
fruits[1] = "mango" # Replaces "orange" with "mango"
print(fruits) # Output: ['apple', 'mango', 'banana', 'coconut']
# Add an item to the end
fruits.append("pineapple")
print(fruits) # Output: ['apple', 'mango', 'banana', 'coconut', 'pineapple']
# Remove an item by its value
fruits.remove("banana")
print(fruits) # Output: ['apple', 'mango', 'coconut', 'pineapple']
This next part of the Bro Code video covers accessing elements and some of the most common list methods.
Python lists, sets, and tuples explained 🍍
Let's continue with the same video to learn about accessing and manipulating list items. The video covers more methods than you need to memorize right now, so focus on the core ideas.
Watch from 01:42 to 09:38. Focus on understanding indexing, the len() function to get the list's size, and the append(), remove(), and insert() methods.
Iterating Through a List with for Loops
One of the most common tasks is to perform an action on every item in a list. This is called iteration, and we use a for loop to do it. This is where lists become truly powerful. For your text analysis tool, you might loop through a list of sentences to analyze each one.
The video below clearly demonstrates the two main ways to loop through a list.
This video from Neso Academy provides a focused explanation of how to use for loops to iterate through a list.
Watch the entire video (from 00:34 to 06:54). It covers the simple for item in list syntax and the more complex for i in range(len(list)) method, which is also useful to know.
As you saw, the simplest method is:
cars = ["Audi", "BMW", "Toyota"]
for car in cars:
print(f"I would like to buy a {car}.")
This is clean, readable, and the most common way to iterate through a list in Python.
Dictionaries: Storing Key-Value Pairs
What if the order of items doesn't matter, but you need to look up information associated with a specific "label"? For example, if you have a person's contact info, you want to look up their email by knowing it's their "email", not by remembering it's the 3rd item in a list.
This is where dictionaries come in. Dictionaries store data in key-value pairs. You use a unique key (like "name" or "email") to retrieve its associated value.
What are Dictionaries?
You create dictionaries using curly braces {}. Each pair consists of a key, a colon :, and a value.
# A dictionary representing a user
user = {
"username": "a_turing",
"email": "alan@bletchleypark.org",
"posts": 12
}
To understand the concept of key-value pairs and how dictionaries differ from lists, please read the following introduction.
Master Python Dictionaries: The Ultimate Beginner's Guide ...
This article from Medium provides an excellent beginner's guide to dictionaries. These first sections will introduce the core concept and show you how to create them.
Read the sections titled 'What is a Dictionary in Python?' and 'How to Create a Dictionary in Python'. Focus on the key-value pair concept and the curly brace {} syntax.
Accessing and Modifying Dictionary Data
Just like with lists, you'll need to access, add, change, and remove data from your dictionaries. Instead of using a numerical index, you use the key.
# Access a value by its key
print(user["email"]) # Output: alan@bletchleypark.org
# Add a new key-value pair
user["is_active"] = True
print(user)
# Modify an existing value
user["posts"] = 13
print(user)
# Remove a key-value pair
del user["is_active"]
print(user)
Now, let's learn the common ways to work with dictionary data by reading the next section of the same article.
Master Python Dictionaries: The Ultimate Beginner's Guide ...
This section of the article details how to get, set, and remove data from a dictionary. Pay special attention to the .get() method, which is a safe way to access data that might not exist.
Read the section titled 'Accessing and Modifying Dictionary Values'. Note the difference between accessing with [] (which can cause an error) and using .get().
Test your understanding!
Given the following dictionary, how would you update the major to "Data Science" and add a new key year with the value 3?
student = {"name": "John Doe", "age": 20, "major": "Computer Science"}
Show answer
# Update the major
student["major"] = "Data Science"
# Add the new key-value pair
student["year"] = 3
print(student)
# Output: {'name': 'John Doe', 'age': 20, 'major': 'Data Science', 'year': 3}
Iterating Through Dictionaries
Looping through dictionaries is also a common task. For your project, you could loop through a dictionary of word counts to find the most common word. You can loop through a dictionary's keys, its values, or its key-value pairs. The .items() method is especially useful for getting both at once.
The following reading explains this clearly.
How to Implement Python Loops for Lists, Tuples, and ...
This article from Bottega Devcamp provides a concise guide to looping through different data structures. We will focus on the dictionary part.
Read the part that starts with 'Now let's talk about how we can work with dictionaries.' until you see the 'IndentationError' heading. Focus on the for position, player in players.items(): syntax, which is the standard way to loop through both keys and values.
Here's the key pattern you'll use most often:
word_counts = {"hello": 5, "world": 3, "python": 8}
for word, count in word_counts.items():
print(f"The word '{word}' appeared {count} times.")
Combining Lists and Dictionaries
The real power comes when you combine these data structures. A very common pattern is a list of dictionaries. Imagine a list of users, where each user is a dictionary containing their details.

Here's how you would work with a structure like that:
people = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Get the first person's name
print(people[0]['name']) # Output: Alice
# Loop through everyone and print their info
for person in people:
print(f"{person['name']} is {person['age']} years old.")
This pattern will be invaluable for organizing the data in your web application.
Try It Yourself: Task Manager
Let's build a very simple task manager to practice these concepts.
-
Create a new file called
task_manager.py. -
Start with a list of dictionaries, where each dictionary represents a task. Each task should have a
'description'(a string) and a'completed'status (a boolean).tasks = [ {'description': 'Finish Python lesson', 'completed': True}, {'description': 'Plan web app features', 'completed': False}, {'description': 'Go grocery shopping', 'completed': False} ] -
Write a
forloop that iterates through thetaskslist. -
Inside the loop, use an
if/elsestatement to check the'completed'status of each task. -
Print a formatted string for each task, indicating whether it's done or not. For example:
[x] Finish Python lesson[ ] Plan web app features[ ] Go grocery shopping
Hint
You will need to access the values for 'description' and 'completed' for each dictionary inside your loop.
for task in tasks:
description = task['description']
is_completed = task['completed']
# Now use an if statement to decide what to print...
Solution
tasks = [
{'description': 'Finish Python lesson', 'completed': True},
{'description': 'Plan web app features', 'completed': False},
{'description': 'Go grocery shopping', 'completed': False}
]
print("Your To-Do List:")
for task in tasks:
if task['completed']:
status = 'x'
else:
status = ' '
print(f"[{status}] {task['description']}")
# Let's add a new task and print the list again
print("\nAdding a new task...")
tasks.append({'description': 'Start building the app UI', 'completed': False})
print("\nUpdated To-Do List:")
for task in tasks:
if task['completed']:
status = 'x'
else:
status = ' '
print(f"[{status}] {task['description']}")
Key Takeaways
Great job! You now have the tools to manage collections of data, which is a massive leap forward.
- Lists (
[]) store ordered collections of items, accessed by a numerical index (starting at 0). - Dictionaries (
{}) store unordered collections of key-value pairs, accessed by a unique key. - Both are iterable, meaning you can use a
forloop to go through their items. - The
for item in my_list:pattern is standard for lists. - The
for key, value in my_dict.items():pattern is standard for dictionaries. - Combining lists and dictionaries (like a list of dictionaries) allows you to model complex, real-world data.
Next Steps
We've written code to loop through lists and print information. But what if we want to perform that same action in multiple places in our program? Copying and pasting code is inefficient and error-prone.
In the next lesson, we will learn how to write functions. Functions allow us to package blocks of code into reusable, named units. This will make our code much more organized, readable, and efficient—essential for building a larger application.