No history yet

Data Structure Iteration

Looping Through Collections

You already know that for loops are Python's workhorse for repetitive tasks. They work by processing one item at a time from a sequence. For lists and tuples, this process is straightforward. The loop assigns each element, in order, to your loop variable.

# Iterating over a list
artists = ["Kendrick Lamar", "SZA", "Tyler, the Creator"]
for artist in artists:
    print(f"{artist} is a Grammy winner.")

# Output:
# Kendrick Lamar is a Grammy winner.
# SZA is a Grammy winner.
# Tyler, the Creator is a Grammy winner.

If artists were a tuple instead of a list, the code and the output would be identical. The loop simply moves from the first element to the last.

Sets are different. Since they are unordered collections, Python doesn't guarantee the sequence of iteration. When you loop over a set, you'll get every item exactly once, but you can't be sure in which order they will appear.

genres = {"hip-hop", "R&B", "jazz", "soul"}
for genre in genres:
    print(f"Found genre: {genre}")

# Possible Output (order might change on each run):
# Found genre: soul
# Found genre: R&B
# Found genre: hip-hop
# Found genre: jazz

This unordered nature is a direct result of how sets are optimized for fast membership checking, not for maintaining sequence. All of these data structures, lists, tuples, and sets, are considered because a for loop can step through them.

Navigating Dictionaries

Dictionaries present a unique challenge because they store key-value pairs. What should a for loop give you? The key, the value, or both?

By default, iterating directly over a dictionary gives you its keys.

album_sales = {
    "Thriller": 40_000_000,
    "Back in Black": 25_000_000,
    "The Dark Side of the Moon": 24_000_000
}

print("Albums:")
for album in album_sales:
    print(album)

# Output:
# Albums:
# Thriller
# Back in Black
# The Dark Side of the Moon

This is useful, but often you need the values or both the key and the value. Dictionaries have specific methods for these situations. To get only the values, use the .values() method.

print("\nSales figures:")
for sales in album_sales.values():
    print(sales)

# Output:
# Sales figures:
# 40000000
# 25000000
# 24000000

The most powerful method is .items(). It gives you access to both the key and the value during each loop iteration. It returns a sequence of key-value tuples, which you can unpack directly into two loop variables.

print("\nFull report:")
for album, sales in album_sales.items():
    print(f"{album}: {sales} copies sold.")

# Output:
# Full report:
# Thriller: 40000000 copies sold.
# Back in Black: 25000000 copies sold.
# The Dark Side of the Moon: 24000000 copies sold.

Using .items() is the standard, most Pythonic way to loop through a dictionary when you need both keys and values. The methods .keys(), .values(), and .items() return special that provide a dynamic window into the dictionary's entries.

Mastering these iteration patterns is key to processing real-world data, which often comes in the form of nested lists and dictionaries.

Quiz Questions 1/4

Consider the following Python code:

my_set = {'apple', 'banana', 'cherry'}
for fruit in my_set:
    print(fruit)

What is the most accurate description of the output?

Quiz Questions 2/4

If you iterate directly over a dictionary (e.g., for item in my_dict:), what will the loop variable item represent during each iteration by default?