# Initialize Otter
import otter
grader = otter.Notebook("05_lecture_for_loops.ipynb")
For Loops in Python¶
Theme: Spotify Wrapped - Analyzing your music listening history
Goal: Learn for loops from first principles, including why they exist (vs while loops), the range() function, iterating over lists, running totals, finding max/min values, nested loops, and importing libraries like tqdm.
By the end of this notebook, you will be able to:
- Explain when to use a
forloop vs awhileloop - Write count-controlled loops using
range(start, stop, step) - Iterate directly over lists using
for item in list - Use index-based iteration to access parallel lists
- Calculate running totals within a for loop
- Track a maximum/minimum value across iterations
- Write simple nested for loops
- Use
tqdmfor progress bars (importing from libraries)
Reference: You can look back at 04_lecture_while_loops.ipynb for help with while loops and 03_decision_structures_boolean_logic.ipynb for conditionals!
Important: Run cells in order from top to bottom. Later questions use variables from earlier cells.
# Validation: Check Python version and file location
import os
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "05_lecture_for_loops.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
Your Spotify Wrapped Data¶
Before we start learning about for loops, let's set up our data. Here's a mock Spotify listening history with 15 songs stored in parallel lists - each list stores a different piece of information about the same songs, in the same order.
A list is a collection of values stored together - like a playlist. We'll learn more about lists formally later, but for now think of them as containers that hold multiple values. The for loop is the perfect tool for processing them.
# --- Your 2025 Spotify Wrapped Data ---
# These are "parallel lists" - index 0 in each list refers to the same song
song_titles = [
"Espresso", "Blinding Lights", "Anti-Hero", "Cruel Summer",
"Levitating", "Heat Waves", "As It Was", "Flowers",
"Bad Habit", "Shake It Off", "Good 4 U", "Watermelon Sugar",
"drivers license", "Stay", "Peaches"
]
artists = [
"Sabrina Carpenter", "The Weeknd", "Taylor Swift", "Taylor Swift",
"Dua Lipa", "Glass Animals", "Harry Styles", "Miley Cyrus",
"Steve Lacy", "Taylor Swift", "Olivia Rodrigo", "Harry Styles",
"Olivia Rodrigo", "The Kid LAROI", "Justin Bieber"
]
play_counts = [84, 47, 62, 58, 35, 28, 41, 33, 19, 55, 31, 22, 38, 24, 15]
durations_min = [2.9, 3.3, 3.2, 3.0, 3.4, 4.0, 2.8, 3.3, 3.9, 3.7, 3.0, 2.9, 4.0, 2.4, 3.3]
genres = [
"pop", "r&b", "pop", "pop", "pop", "indie", "pop", "pop",
"r&b", "pop", "pop", "pop", "pop", "pop", "pop"
]
print(f"Loaded {len(song_titles)} songs!")
print(f"Example: song_titles[0] = '{song_titles[0]}' by artists[0] = '{artists[0]}'")
print(f" Played {play_counts[0]} times, {durations_min[0]} min each, genre: {genres[0]}")
1. The Big Picture¶
Before we dive into individual concepts, let's see what you'll be able to build by the end of this notebook. Here's a complete function that generates a mini Spotify Wrapped summary using all the concepts we'll learn:
forloops withrange()- Iterating over lists
- Running totals (total listening time)
- Max tracking (most-played song)
- Nested loops (unique artists)
Don't worry if you don't understand every line yet! By the end of these two lectures, you'll be able to write this yourself.
# THE BIG PICTURE: Complete Spotify Wrapped generator
# By the end of this notebook, you'll understand every line!
def generate_wrapped(titles, artist_list, plays, durations):
"""
Generate a mini Spotify Wrapped summary.
Demonstrates: for loop, range(), list iteration, running total, max tracking, nested loop
"""
print("=" * 40)
print(" YOUR 2025 SPOTIFY WRAPPED")
print("=" * 40)
# --- Total listening time (running total with for loop) ---
total_min = 0.0
for i in range(len(titles)):
total_min += plays[i] * durations[i]
print(f"\nTotal listening time: {total_min / 60:.1f} hours")
# --- Your Top 5 (for loop with range) ---
print("\n--- Your Top 5 ---")
for rank in range(5):
print(f" #{rank + 1}: {titles[rank]} by {artist_list[rank]}")
# --- Most played song (for loop + max tracking) ---
top_song = titles[0]
top_plays = plays[0]
for i in range(1, len(titles)):
if plays[i] > top_plays:
top_song = titles[i]
top_plays = plays[i]
print(f"\nMost Played: {top_song} ({top_plays} plays)")
# --- Unique artists (for loop + 'in' check) ---
unique = []
for artist in artist_list:
if artist not in unique:
unique.append(artist)
print(f"You listened to {len(unique)} different artists")
print("=" * 40)
# Run it!
generate_wrapped(song_titles, artists, play_counts, durations_min)
Now let's learn each piece!
We'll analyze our Spotify data step by step, building up to that complete function.
Day 1: For Loop Foundations¶
2. From While to For¶
You already know while loops from the parking lot lecture. A for loop solves the same problem more cleanly when you know how many times to repeat.
Remember searching for parking? We didn't know how many laps it would take to find a spot - that's a while loop. But we have exactly 15 songs in our Spotify data. We KNOW how many to process. That's a for loop.
# --- WHILE loop: Print songs 1 through 5 ---
i = 0
while i < 5:
print(f"Song {i + 1}: {song_titles[i]}")
i += 1 # Don't forget this or INFINITE LOOP!
print("---")
# --- FOR loop: Same thing, but cleaner ---
for i in range(5):
print(f"Song {i + 1}: {song_titles[i]}")
# No manual counter needed! range() handles it
Notice the for loop doesn't need i = 0 before the loop or i += 1 inside it. The range() function handles all of that for you.
When to use which:
| Situation | Use |
|---|---|
| You KNOW how many times to repeat | for loop |
| You DON'T know when to stop | while loop |
| Process every item in a list | for loop |
| Wait for user input / event | while loop |
3. range() - Your Loop Counter¶
The range() function generates a sequence of numbers for your loop. It's the most common way to control a for loop.
3.1 range(n) - Count from 0 to n-1¶
# range(n) counts from 0 to n-1
# Let's SEE what it produces by converting to a list
print("range(5) produces:", list(range(5)))
print()
# Use it in a for loop to print your top 5 songs
for i in range(5):
print(f" i = {i} --> Song: {song_titles[i]}")
3.2 range(start, stop) - Count from start to stop-1¶
# range(start, stop) counts from start to stop-1
print("range(3, 8) produces:", list(range(3, 8)))
print()
# Print songs 4 through 8 (indices 3 through 7)
print("Songs 4 through 8 (index 3 through 7):")
for i in range(3, 8):
print(f" i = {i} --> #{i + 1}: {song_titles[i]}")
3.3 range(start, stop, step) - Custom step size¶
# range(start, stop, step) with custom step size
print("range(0, 15, 2) produces:", list(range(0, 15, 2)))
print()
# Print every other song
print("Every other song:")
for i in range(0, len(song_titles), 2):
print(f" #{i + 1}: {song_titles[i]}")
3.4 Counting backwards¶
# Counting down: range(start, stop, step) with negative step
print("range(5, 0, -1) produces:", list(range(5, 0, -1)))
print()
# Countdown - your top 5 in reverse
print("Countdown - your top 5 in reverse:")
for i in range(4, -1, -1):
print(f" #{i + 1}: {song_titles[i]}")
Key intuition: Think of range(start, stop) like a fence - the stop value is the fence post you walk UP TO but never step on.
range(5)=[0, 1, 2, 3, 4]- stops BEFORE 5range(3, 8)=[3, 4, 5, 6, 7]- stops BEFORE 8range(0, 15, 2)=[0, 2, 4, 6, 8, 10, 12, 14]- stops BEFORE 15
Question 1: Print Your Top 5 (1 point)¶
Use a for loop with range() to build a string showing your top 5 songs, numbered 1 through 5.
Store the result in top_5_display. Each song should be on its own line in this format:
#1: Espresso by Sabrina Carpenter
#2: Blinding Lights by The Weeknd
(and so on through #5)
Hint: Start with an empty string and use += to add each line with a \n at the end.
# ✏️ YOUR CODE HERE
top_5_display = ...
...
...
print(top_5_display)
grader.check("q1_top_five")
# When you just need each item, iterate directly
# The variable "song" takes on each value in the list, one at a time
print("All songs in your library:")
for song in song_titles:
print(f" {song}")
4.2 Index-Based Iteration - When you need to access multiple lists¶
When you need values from multiple lists at the same position, use an index with range(len(...)):
# When you need to access MULTIPLE lists at the same position, use an index
print("Songs with play counts:")
for i in range(len(song_titles)):
print(f" {song_titles[i]} by {artists[i]} - {play_counts[i]} plays")
4.3 Tracing Through a Loop¶
Let's trace through exactly what happens at each step. Adding print() statements inside loops is a great way to understand and debug them:
# Let's trace through exactly what happens, step by step
# (Just first 3 to keep output short)
for i in range(3):
print(f"--- Iteration: i = {i} ---")
print(f" song_titles[{i}] = '{song_titles[i]}'")
print(f" artists[{i}] = '{artists[i]}'")
print(f" play_counts[{i}] = {play_counts[i]}")
print()
Which approach should I use?
| Need | Approach | Example |
|---|---|---|
| Values from ONE list | Direct: for item in list |
for song in song_titles: |
| Values from MULTIPLE lists | Index: for i in range(len(list)) |
for i in range(len(song_titles)): |
Reference to parking lot: Remember checking one row at a time? A for loop handles all 15 songs automatically!
Question 2: Count the Taylor Swift Songs (1 point)¶
Count how many songs in your library are by Taylor Swift. Loop through the artists list and count each match.
Store the count in swift_count.
Hint: Same counter pattern as counting laps in the parking lot - start at 0, add 1 each time you find a match. But now the for loop handles the iteration for you.
# ✏️ YOUR CODE HERE
swift_count = ...
...
...
print(f"Taylor Swift songs: {swift_count}")
grader.check("q2_swift_count")
Day 2: Patterns and Power¶
Quick recap from Day 1:
forloops repeat code a known number of timesrange(n)counts from 0 to n-1;range(start, stop, step)gives full control- Iterate directly (
for song in songs) when you need one list - Use index-based (
for i in range(len(songs))) when you need multiple lists
Now let's learn the powerful patterns that make for loops really useful.
5. Running Totals¶
The accumulator pattern adds up values across loop iterations. You saw this in the parking lot with total_time - same idea, but the for loop handles counting for us.
Reference: Remember tracking total_time while searching for parking? Same accumulator pattern: start at zero, add each iteration.
# How many total plays across ALL songs?
total_plays = 0
for plays in play_counts:
print(f" Adding {plays} plays... total so far: {total_plays} + {plays} = {total_plays + plays}")
total_plays += plays
print(f"\nTotal plays across all songs: {total_plays}")
# Total listening time = sum of (plays * duration) for each song
# This requires index-based iteration since we need TWO lists
total_minutes = 0.0
for i in range(len(song_titles)):
song_minutes = play_counts[i] * durations_min[i]
total_minutes += song_minutes
print(f" {song_titles[i]}: {play_counts[i]} x {durations_min[i]} min = {song_minutes:.1f} min (total: {total_minutes:.1f})")
print(f"\nTotal: {total_minutes:.1f} minutes = {total_minutes / 60:.1f} hours")
The accumulator pattern:
total = 0 # 1. Start at zero
for item in collection:
total += item # 2. Add each value
print(total) # 3. Use the result AFTER the loop
Common mistake: Putting print(total) INSIDE the loop prints the running total at every step (useful for debugging), but putting it AFTER the loop prints just the final answer.
Question 3: Total Listening Time (1 point)¶
Calculate the total time you spent listening to music this year.
For each song, the listening time is play_counts[i] * durations_min[i] (plays times minutes per play). Sum all of these to get total minutes, then convert to hours by dividing by 60.
Store the total minutes in listening_minutes and the hours in listening_hours.
Hint: Use an index-based for loop since you need values from two parallel lists.
# ✏️ YOUR CODE HERE
listening_minutes = ...
...
...
listening_hours = ...
print(f"Total listening time: {listening_minutes:.1f} minutes = {listening_hours:.1f} hours")
grader.check("q3_total_listening")
6. Finding the Maximum (or Minimum)¶
A new pattern: track the best so far. Assume the first item is the best, then check every other item. If you find something better, update your "best" variables.
Reference: Remember using if/elif chains to check grade ranges? Now we can find the best among ANY number of items automatically!
# Find the most-played song
# Strategy: assume the first song is the best, then check every other song
best_title = song_titles[0]
best_plays = play_counts[0]
print(f"Starting assumption: '{best_title}' with {best_plays} plays\n")
for i in range(1, len(song_titles)): # Start at 1 - we already have index 0
current_title = song_titles[i]
current_plays = play_counts[i]
if current_plays > best_plays:
print(f" [{i}] {current_title} ({current_plays} plays) > {best_title} ({best_plays} plays) --> NEW BEST!")
best_title = current_title
best_plays = current_plays
else:
print(f" [{i}] {current_title} ({current_plays} plays) <= {best_title} ({best_plays} plays)")
print(f"\nMost played: '{best_title}' with {best_plays} plays")
The max-tracking pattern:
best = collection[0] # 1. Assume first is best
for i in range(1, len(collection)):
if collection[i] > best: # 2. Found something better?
best = collection[i] # 3. Update the best
print(best) # 4. Use result AFTER loop
For minimum, just change > to <.
Question 4: Most-Played Song (1 point)¶
Find the title of your most-played song. Loop through all songs, tracking which one has the highest play count.
Store the title in most_played_title and the play count in most_played_count.
Hint: Start by assuming the first song is the most-played. Then loop from index 1 onward, updating whenever you find a song with more plays.
# ✏️ YOUR CODE HERE
most_played_title = ...
most_played_count = ...
...
...
most_played_title = ...
most_played_count = ...
print(f"Most played: {most_played_title} ({most_played_count} plays)")
grader.check("q4_most_played")
7. Nested For Loops¶
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
# Nested loops: inner loop runs COMPLETELY for each outer iteration
for outer in range(3):
for inner in range(4):
print(f" outer={outer}, inner={inner}")
print(f"--- outer {outer} finished ---\n")
Using Nested Loops: Finding Unique Items¶
One common use of nested loops is checking if something is already in a list. Let's find all the unique artists in our library:
# Find all unique artists using a nested loop approach
unique_artists = []
for artist in artists:
# Check if we've seen this artist before
already_seen = False
for seen_artist in unique_artists:
if artist == seen_artist:
already_seen = True
if not already_seen:
unique_artists.append(artist)
print(f" New artist found: {artist}")
else:
print(f" Already have: {artist}")
print(f"\nUnique artists ({len(unique_artists)}): {unique_artists}")
The in Shortcut¶
Python has a built-in shortcut for "is this item in the list?" - the in keyword. This replaces the inner loop entirely:
# Simpler version using 'in' (replaces the inner loop!)
unique_artists_v2 = []
for artist in artists:
if artist not in unique_artists_v2:
unique_artists_v2.append(artist)
print(f"Unique artists: {unique_artists_v2}")
print(f"Count: {len(unique_artists_v2)}")
Both approaches produce the same result, but in is cleaner. Under the hood, in does the same inner loop for you.
Question 5: Count Unique Genres (1 point)¶
How many different genres are in your library? Build a list of unique genres from the genres list, then count how many there are.
Store the list in unique_genres and the count in unique_genre_count.
Hint: Use the not in shortcut to check if a genre is already in your unique list.
# ✏️ YOUR CODE HERE
unique_genres = ...
...
...
unique_genre_count = ...
print(f"Unique genres: {unique_genres} ({unique_genre_count} genres)")
grader.check("q5_unique_genres")
8. tqdm and Importing from Libraries¶
Python has thousands of libraries that other people have written. To use them, you import them. Let's try tqdm - a library that adds progress bars to your loops.
Key point: tqdm is a library someone else wrote. We import it with from tqdm import tqdm. You'll see this import pattern a lot in Python.
from tqdm import tqdm
# tqdm wraps any iterable and shows a progress bar
# Just replace range(n) with tqdm(range(n))!
print("Processing your library:")
for song in tqdm(song_titles, desc="Songs"):
pass # We're not doing anything, just showing the progress bar
import time
from tqdm import tqdm
# Simulate "generating" your Wrapped report with a progress bar
total_play_count = 0
for i in tqdm(range(len(song_titles)), desc="Analyzing songs"):
total_play_count += play_counts[i]
time.sleep(0.15) # Slow it down so you can see the bar
print(f"\nDone! Total plays: {total_play_count}")
Question 6: Top Artist by Total Plays (1 point)¶
Find the artist with the most total plays across all their songs. This combines nested loops, running totals, and max tracking!
Steps:
- Build a list of unique artists (you did this in Q5 for genres - same pattern)
- For each unique artist, use an inner loop to sum up all their play counts
- Track which artist has the highest total (max-tracking pattern from Q4)
Store the artist name in top_artist and their total plays in top_artist_plays.
Example: Taylor Swift has 3 songs with 62 + 58 + 55 = 175 total plays.
# ✏️ YOUR CODE HERE
# Step 1: Build unique artists list
unique_artist_list = ...
...
...
# Step 2 & 3: Find artist with most total plays
top_artist = ...
top_artist_plays = ...
...
artist_total = ...
...
...
...
top_artist = ...
top_artist_plays = ...
print(f"Top artist: {top_artist} ({top_artist_plays} total plays)")
grader.check("q6_top_artist")
Stretch Goal: All-in-One Wrapped Stats (1 bonus point)¶
Combine your skills! In a single for loop, simultaneously:
- Count the total number of songs (
wrapped_song_count) - Calculate total listening time in hours, rounded to 1 decimal (
wrapped_total_hours) - Find the most-played song (
wrapped_top_songandwrapped_top_plays)
The challenge: do all three computations in ONE loop instead of three separate loops.
Hint: Initialize all variables before the loop, then update all of them inside each iteration.
# ✏️ YOUR CODE HERE
wrapped_song_count = ...
wrapped_total_min = ...
wrapped_top_song = ...
wrapped_top_plays = ...
...
...
...
...
wrapped_top_song = ...
wrapped_top_plays = ...
wrapped_total_hours = ...
print("=== YOUR 2025 WRAPPED ===")
print(f"Total songs: {wrapped_song_count}")
print(f"Total listening time: {wrapped_total_hours} hours")
print(f"Most played: {wrapped_top_song} ({wrapped_top_plays} plays)")
grader.check("q7_stretch_wrapped")
Summary¶
Congratulations! You've learned how to use for loops to analyze your Spotify data!
| Concept | Syntax | Spotify Example |
|---|---|---|
| Basic for | for item in collection: |
for song in song_titles: |
| range(n) | for i in range(n): |
for i in range(5): (top 5) |
| range(start, stop) | for i in range(a, b): |
for i in range(5, 10): (songs 6-10) |
| range(start, stop, step) | for i in range(a, b, c): |
for i in range(0, 15, 2): (every other) |
| Counting backwards | range(n, -1, -1) |
Reverse countdown |
| Running total | total += value |
listening_minutes += song_time |
| Max tracking | if val > best: best = val |
Find most-played song |
| Nested loops | loop inside a loop | For each artist, count their songs |
| tqdm | for x in tqdm(items): |
Progress bar while processing |
| For vs While | for = known count, while = unknown | 15 songs (for) vs parking search (while) |
Key Takeaways¶
- For loops iterate a known number of times - use when you know how many repetitions
range()generates sequences -range(5)=[0, 1, 2, 3, 4](stops BEFORE 5)- Two ways to iterate: directly (
for song in songs) or by index (for i in range(len(songs))) - Running totals start at zero and accumulate with
+=inside the loop - Max/min tracking: assume first is best, update when you find better
- Nested loops: inner loop runs completely for each outer iteration
tqdmadds progress bars - import it and wrap your iterable
What's Next?¶
- Lab: Practice these patterns with more complex exercises
- Next Week: Lists in depth - methods, slicing, and more!
Submitting to Gradescope¶
This file is saved on your computer — you do not need to download it from Jupyter.
Find the file on your computer:
- Mac: Open Finder →
Documents/CSC115/lecture_notebooks/05_lecture_for_loops/05_lecture_for_loops.ipynb - Windows: Open File Explorer →
Documents\CSC115\lecture_notebooks\05_lecture_for_loops\05_lecture_for_loops.ipynb
- Mac: Open Finder →
Upload to Gradescope:
- Go to gradescope.com and open this assignment
- Click "Submit" and upload the
.ipynbfile - The filename must be exactly
05_lecture_for_loops.ipynb
Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.
You have completed the For Loops in Python notebook.
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()