Iterating Through Lists

SA
StudyAI
AI-generated study notes
· Published Updated

From the PYTHON curriculum

TL;DR

Iterating through a list means going through each item one by one to do something with it. Python's for loop is the most common way to do this efficiently. You can access both the item itself and its index if you need to know its position.

1. The Mental Model

Think of a list as a line of people. Iterating means you're walking down the line, greeting each person individually. You perform an action (like saying "hello") on each person before moving to the next.

2. The Core Material

When you iterate through a list in Python, you're essentially telling the computer to visit every element in that list, from the first one to the last. This is super useful when you need to process, display, or modify items within a collection.

Using a for loop

A surreal abstract 3D render featuring an infinity symbol with a warm, textured background.
Photo by Steve A Johnson on Pexels

The most straightforward way to iterate is using a for loop. This loop will assign each item in the list to a temporary variable, one at a time, for each pass through the loop.

my_fruits = ["apple", "banana", "cherry"]

for fruit in my_fruits:
    print(f"I like {fruit}s.")

Output:

I like apples.
I like bananas.
I like cherrys.

Iterating with range() and len()

A stunning mountain range seen through sunglasses, highlighting natural beauty.
Photo by Soumyojit Sinha on Pexels

Sometimes you need to know the index (position) of the item as you iterate. You can do this by combining range() and len(). len(my_list) gives you the number of items, and range(number) generates a sequence of numbers from 0 up to (but not including) number.

my_fruits = ["apple", "banana", "cherry"]

for index in range(len(my_fruits)):
    fruit = my_fruits[index] # Access the item using its index
    print(f"Fruit at index {index} is {fruit}.")

Output:

Fruit at index 0 is apple.
Fruit at index 1 is banana.
Fruit at index 2 is cherry.

Using enumerate()

Hands typing code on a laptop in a workspace. Indoor setting focused on software development.
Photo by cottonbro studio on Pexels

The enumerate() function is often a more Pythonic (and often clearer) way to get both the index and the item simultaneously. It returns pairs of (index, item).

my_fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(my_fruits):
    print(f"Index {index}: {fruit}")

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

How Iteration Works

Young professionals brainstorming and designing a product prototype on a whiteboard.
Photo by Thirdman on Pexels

Here's a simple flow of how a for loop iterates through a list:

graph TD
    A["Start Iteration"] --> B{"Is there a next item?"};
    B -- Yes --> C["Get the next item"];
    C --> D["Assign item to loop variable"];
    D --> E["Execute code inside loop"];
    E --> B;
    B -- No --> F["End Iteration"];

3. Worked Example

Let's say you have a list of temperatures and you want to convert each one from Celsius to Fahrenheit, then print the new temperature.

Given list:
celsius_temps = [0, 10, 20, 30, 40]

Conversion formula: Fahrenheit = (Celsius * 9/5) + 32

celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = [] # An empty list to store the results

for temp_c in celsius_temps:
    temp_f = (temp_c * 9/5) + 32
    fahrenheit_temps.append(temp_f) # Add the converted temp to our new list
    print(f"{temp_c}°C is {temp_f}°F")

print("\nAll Fahrenheit temperatures:", fahrenheit_temps)

Output:

0°C is 32.0°F
10°C is 50.0°F
20°C is 68.0°F
30°C is 86.0°F
40°C is 104.0°F

All Fahrenheit temperatures: [32.0, 50.0, 68.0, 86.0, 104.0]

4. Key Takeaways

  • Use a for loop to process each item in a list.
  • The for item in list: syntax directly gives you each item.
  • Use for index in range(len(list)): when you explicitly need the item's position.
  • enumerate(list) is a neat way to get both the index and the item at once.
  • Iterating lets you perform actions on all elements without repetitive code.
  • Lists are ordered, so iteration follows that order.

Common mistakes to avoid:
- Don't try to modify a list (add/remove items) while you're iterating directly over it; it can lead to unexpected behavior. Iterate over a copy or build a new list instead.
- Forgetting that range(len(list)) starts indexing at 0.
- Confusing the item itself with its index when using for item in list:.
- Using while loops for simple list iteration when a for loop is much clearer and less error-prone.

5. Now Try It

Create a list of your 5 favorite animals. Then, use a for loop to print each animal name, capitalized, with the text "My favorite animal is a ". For example, if "cat" is in your list, it should print "My favorite animal is a Cat".

Frequently asked about Iterating Through Lists

Iterating through a list means going through each item one by one to do something with it. Python's for loop is the most common way to do this efficiently. You can access both the item itself and its index if you need to know its position. Think of a list as a line of people. Read the full notes above for the details.

Iterating Through Lists is a core topic in PYTHON. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Modifying List Elements

More from PYTHON


Get the full PYTHON curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Save this course free