Lesson 3 · Python For Time Series
Master Python Data Structures: Lists, Tuples, Sets & Dictionaries Explained Clearly
In this lesson, we will explore four important Python data structures. You will learn what they are, how to use them, and see examples from real data. Let…
- CoursePython For Time Series
- Lesson3 of 30
- Video28 min
- FormatJupyter notebook · 24 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynb
Welcome to Python: Lists, Tuples, Sets, and Dictionaries!#
In this lesson, we will explore four important Python data structures.
You will learn what they are, how to use them, and see examples from real data.
Let us get started!
import warnings
warnings.filterwarnings("ignore")
# Suppress warnings to keep things tidy
What are Lists, Tuples, Sets, and Dictionaries?#
Imagine you have to manage a shopping list, a group of coordinates, a set of unique badges, and a directory of names to phone numbers.
- Lists hold ordered sets of items (like a shopping list).
- Tuples are like lists, but you cannot change them after creation.
- Sets hold only unique items, with no order.
- Dictionaries map a key to a value, like a name to a phone number.
# Lists: Store any group of items, like a shopping list
shopping = ["apples", "bread", "milk", "eggs"]
print(shopping)
# Tuples: Similar to lists, but cannot be changed
coordinates = (10, 20)
print(coordinates)
# Sets: Unordered, no duplicates
my_badges = set(["python", "data", "python", "study"])
print(my_badges)
# Dictionaries: Key-value pairs, like a contact list
contacts = {"Alice": "1234", "Bob": "5678"}
print(contacts)
Accessing Data Safely#
We can get items from lists, tuples, and dictionaries.
But what if you try to access something that is not there?
Let us see examples.
# Accessing a list by index
print(shopping[1]) # bread
# Accessing a dictionary by key
print(contacts["Bob"])
# Safe dictionary access: get() returns None if missing (or your default)
print(contacts.get("Charlie")) # Not found
print(contacts.get("Charlie", "N/A")) # Not found, uses your default value
Updating and Changing Data#
Let us add, update, and remove items in these structures.
Tuples cannot be changed, but lists, sets, and dictionaries can!
# Adding and updating a list
shopping.append("butter")
shopping[0] = "green apples"
print(shopping)
# Add to a set (only unique items stay)
my_badges.add("study")
my_badges.add("cooking")
print(my_badges)
# Updating or adding to a dictionary
contacts["Charlie"] = "9012"
contacts["Alice"] = "1111"
print(contacts)
# Removing items from collections
shopping.remove("milk")
my_badges.discard("python")
contacts.pop("Bob")
print(shopping)
print(my_badges)
print(contacts)
Useful Built-in Functions and Methods#
Some functions work across these types, like len(), min(), max(), sorted(), and sum() (for numbers).
Let us check some handy ones!
# Quick stats with a list of numbers
temperatures = [22, 19, 25, 20, 23, 19]
print("Length:", len(temperatures))
print("Max:", max(temperatures))
print("Min:", min(temperatures))
print("Sorted:", sorted(temperatures))
Looping Through Collections#
It is common to loop through each item in your list, set, or dictionary.
Let us see how to do this with for loops.
# Loop through a list
for item in shopping:
print("I need to buy", item)
# Loop through a dictionary
for name, number in contacts.items():
print(name, "has number", number)
# List Comprehensions: Build lists quickly
squares = [x * x for x in range(1, 6)]
print(squares)
Real Data Example: Monthly Airline Passengers#
Time to use a real dataset! We are going to download passenger totals by month and explore the data as lists and dictionaries.
Let us get our data.
# Data setup
import pandas as pd
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url)
print("Data shape:", df.shape)
df.head()
# Turn data into lists and a dictionary
months = df["Month"].tolist()
passengers = df["Passengers"].tolist()
monthly_dict = dict(zip(months, passengers))
print(months[:3], "...", len(months))
print(passengers[:3], "...", len(passengers))
print(list(monthly_dict.items())[:3])
# Quick line plot of data
import matplotlib.pyplot as plt
plt.figure(figsize=(10,4))
plt.plot(months, passengers, marker="o")
plt.title("Monthly Airline Passengers")
plt.xlabel("Month")
plt.ylabel("Passengers")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Mini-project: Find the month with the most passengers
max_month = months[passengers.index(max(passengers))]
print("Busiest month:", max_month)
print("Passengers:", max(passengers))
# Mini-project: Count months above average
average = sum(passengers) / len(passengers)
above_avg = [m for m, p in zip(months, passengers) if p > average]
print("Months above average:", len(above_avg))
print(above_avg[:5])
Best Practices and Troubleshooting#
- Be careful with index numbers; lists and tuples start at zero.
- Use get() for safe dictionary access.
- Sets automatically remove duplicates, so do not rely on order.
- Dictionaries are great for fast lookup, but keys must be unique.
Extra Tips and Tricks#
- Use set() to get unique values from any list.
- Use list() to make a new list from a set or tuple.
- Use in to check if an item exists: "apple" in shopping
# Challenge: What do you buy most?
your_list = input("Enter foods, comma separated: ").split(",")
your_set = set([item.strip() for item in your_list])
print("Unique foods:", your_set)
Recap: What Have We Learned?#
You now know:
- Lists are ordered and changeable
- Tuples are ordered but unchangeable
- Sets are unique and fast for membership checks
- Dictionaries pair keys with values for quick lookup
You worked with real data and solved practical problems!
Thank You for Learning with Us!#
Hit like and subscribe if this lesson helped you!
Check the description for more resources and next steps.
See you in the next Python adventure!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



