Back to Python Notes
Topic #248

Iterating Arrays

By the end of this lesson, you will be able to efficiently loop through Python lists (arrays) using various iteration techniques, including direct access, index-based loops, and unpacking.

What it is

In Python, "arrays" are typically represented by list objects. Iterating over them means visiting each element sequentially to perform an action, such as printing, calculating, or modifying data. The mental model is a conveyor belt: you pick up one item at a time, process it, and move to the next. Related terms include iterables, indices, and unpacking.

Why it matters

  • Data Processing: Essential for cleaning, transforming, or analyzing datasets stored in lists.
  • Algorithm Implementation: Many algorithms (like sorting or searching) require examining every element.
  • User Interface Updates: Used to render lists of items on a screen or console.
  • File Handling: Often used to read lines from a file into a list and process them one by one.

Syntax or steps

The most common pattern is the for loop. You can iterate directly over elements or use indices if you need position information.

  1. Direct Iteration: Use for item in my_list: when you only need the value.
  2. Index Iteration: Use for i in range(len(my_list)): when you need both the index and the value.
  3. Enumerate: Use for i, item in enumerate(my_list): for a cleaner way to get both index and value.

Example

# A simple list of scores
scores = [85, 90, 78, 92]

# 1. Direct iteration (best for just reading values)
print("All scores:")
for score in scores:
    print(score)

# 2. Using enumerate (best for needing position + value)
print("\nScores with positions:")
for index, score in enumerate(scores):
    print(f"Student {index}: Score {score}")

# 3. Modifying elements requires index access
print("\nAdding bonus points:")
for i in range(len(scores)):
    scores[i] += 5
    print(f"Updated Student {i}: {scores[i]}")

Explanation: The first loop simply prints each number. The second uses enumerate() to pair each score with its index automatically. The third loop uses range(len()) because we are modifying the original list; direct iteration cannot change the source list's structure or values effectively without creating new objects.

Common mistakes

  • Modifying while iterating directly: Changing a list's size (adding/removing items) inside a for item in list: loop causes unpredictable behavior. Fix: Iterate over a copy (list[:] ) or use a while loop with indices.
  • Using range(len()) unnecessarily: If you don't need the index, avoid it. It makes code harder to read. Fix: Use direct iteration or enumerate().
  • Confusing tuples and lists: Remember that strings are also iterable. Looping over a string yields characters, not words. Fix: Use .split() first if you want word-level iteration.

When to use it

Method Use When...
for x in list You only need the values and won't modify the list structure.
for i, x in enumerate(list) You need the index for labeling, logging, or conditional logic based on position.
for i in range(len(list)) You need to modify the list elements in place or access neighboring elements via index math.

Practice

Guided Exercise: Create a list of names ["Alice", "Bob", "Charlie"]. Write a loop that prints "Hello, [Name]!" for each person.

Challenge: Given numbers = [1, 2, 3, 4], write a loop that creates a new list containing the squares of these numbers using a list comprehension (an advanced iteration shortcut).

Hint for Challenge: [x**2 for x in numbers]

Quick check

Question: Why should you avoid using for i in range(len(my_list)): if you only need to print the values?

Answer: It is less readable and more verbose than for item in my_list:. Pythonic style prefers direct iteration unless the index is explicitly required.

Summary

Iterating over arrays in Python is fundamental for data manipulation. Choose direct iteration for simplicity, enumerate() when you need position context, and index-based loops only when modifying the list in place. Mastering these patterns leads to cleaner, more efficient code.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Iterating Arrays – FAQs

Quick answers about learning Iterating Arrays in Python.

This free note from Coding Now Tech Institute explains Iterating Arrays in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Iterating Arrays, is 100% free with no signup required.
With focused practice, most students grasp Iterating Arrays in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now