Back to Python
2026-04-287 min read

Object Iterations (Python Programming)

Learn Object Iterations (Python Programming) step by step with clear examples and exercises.

Title: Object Iterations (Python Programming)

Why This Matters

In Python programming, iterating over objects is a fundamental concept that allows us to traverse through collections like lists, dictionaries, tuples, and more. Understanding object iterations is crucial for writing efficient and effective code in various real-world scenarios such as data analysis, web development, and algorithmic problem-solving.

Prerequisites

Before diving into the core concept of object iterations, it is essential to have a solid understanding of Python programming basics:

  1. Variables and data types
  2. Control structures (if-else, for loops, while loops)
  3. Functions
  4. Lists, tuples, sets, and dictionaries
  5. Basic input/output operations
  6. Understanding the concept of mutable and immutable data types

Core Concept

Iterating over objects in Python can be achieved using various methods depending on the type of object you are working with. Let's explore some common ways to iterate through lists, tuples, sets, and dictionaries, as well as how to handle mutable and immutable data types during iteration.

Iterating through lists

To iterate through a list, you can use a for loop:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)

In this example, the for loop initializes the variable number with each element of the list numbers, and the print() function prints the value of number.

Handling mutable data types during iteration

When iterating through a list containing mutable data types (e.g., lists or dictionaries), it's essential to be aware that modifying these objects during iteration can lead to unexpected results:

my_list = [[1, 2], [3, 4], [5, 6]]
for sublist in my_list:
sublist.append(0) # Modifying the list during iteration will affect its order!
for number in sublist:
print(number)

To avoid this issue, you can create a copy of the mutable object before iterating over it or use enumerate() to keep track of the index and modify the original object outside the loop:

my_list = [[1, 2], [3, 4], [5, 6]]
for i, sublist in enumerate(my_list):
sublist.append(0)
for number in sublist:
print(number)

Iterating through tuples

Iterating through a tuple in Python is similar to iterating through a list:

colors = ("red", "green", "blue")
for color in colors:
print(color)

Iterating through sets

Iterating through a set in Python can be done using a for loop or the built-in __iter__() method:

my_set = {"apple", "banana", "orange"}
for fruit in my_set:
print(fruit)
my_set = {"apple", "banana", "orange"}
it = iter(my_set)
print(next(it)) # Prints the first element of the set
print(next(it)) # Prints the second element of the set, and so on...

Iterating through dictionaries

To iterate through a dictionary, you can use the items(), keys(), or values() method to get specific data and then loop through that data:

students = {
"Alice": 23,
"Bob": 24,
"Charlie": 25
}
for student, age in students.items():
print(f"{student} is {age} years old.")

In this example, the items() method returns a list of key-value pairs, which are then unpacked into the variables student and age. The print() function prints the student's name and age.

Handling mutable data types during iteration

When iterating through a dictionary containing mutable data types (e.g., lists or dictionaries), it's essential to be aware that modifying these objects during iteration can lead to unexpected results:

my_dict = {
"Alice": [1, 2],
"Bob": [3, 4],
"Charlie": [5, 6]
}
for student, sublist in my_dict.items():
sublist.append(0) # Modifying the list during iteration will affect its order!
for number in sublist:
print(number)

To avoid this issue, you can create a copy of the mutable object before iterating over it or use enumerate() to keep track of the index and modify the original object outside the loop:

my_dict = {
"Alice": [1, 2],
"Bob": [3, 4],
"Charlie": [5, 6]
}
for student, sublist in my_dict.items():
new_sublist = sublist[:] # Create a copy of the list before modifying it
new_sublist.append(0)
for number in new_sublist:
print(number)

Worked Example

Let's create a simple program that calculates the sum of all numbers in a list and the total number of words in a string, as well as finding the maximum number in a list using iteration:

def calculate_sum(numbers):
total = 0
for number in numbers:
total += number
return total

def count_words(string):
words = string.split()
return len(words)

def find_max(numbers):
max_number = numbers[0]
for number in numbers:
if number > max_number:
max_number = number
return max_number

my_list = [1, 2, 3, 4, 5]
my_string = "This is a sample string"

print("Sum of numbers:", calculate_sum(my_list))
print("Number of words:", count_words(my_string))
print("Maximum number in the list:", find_max(my_list))

In this example, the calculate_sum() function iterates through the list numbers, calculates the sum, and returns it. The count_words() function splits the string into a list of words using the split() method and then counts the number of elements in that list (i.e., the total number of words). The find_max() function finds the maximum number in the list using iteration.

Common Mistakes

  1. Forgetting to initialize the accumulator variable before iterating through a list or dictionary:
def calculate_sum(numbers):
for number in numbers:
print(number) # This will only print the numbers, not sum them!
  1. Iterating through a list or dictionary using an index instead of a variable:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
print(numbers[i])
  1. Using the wrong method to iterate through a dictionary (e.g., using keys() instead of items()):
students = {
"Alice": 23,
"Bob": 24,
"Charlie": 25
}
for student in students.keys():
print(student) # This will only print the keys, not the key-value pairs!

Common Mistakes (subheading)

  1. Modifying mutable data types during iteration:
my_list = [[1, 2], [3, 4], [5, 6]]
for sublist in my_list:
sublist.append(0) # Modifying the list during iteration will affect its order!
for number in sublist:
print(number)

Practice Questions

  1. Write a function that finds the minimum number in a list using iteration.
  2. Write a function that reverses a string using iteration and returns the reversed string as a new string (not modifying the original string).
  3. Write a function that checks if a given word is present in a list of words using iteration.
  4. Write a function that calculates the average age of students in a dictionary.
  5. Write a function that finds all pairs of numbers in a list whose sum equals a given target number using iteration.
  6. Write a function that removes duplicates from a list using iteration and returns a new list without duplicates.
  7. Write a function that sorts a list of dictionaries by a specific key (e.g., age) in ascending or descending order using iteration.
  8. Write a function that merges two dictionaries with the same keys, overwriting the values from the second dictionary with the values from the first one using iteration.

FAQ

  1. Why can't I use for i in range(len(list)) to iterate through a list?

Using an index to iterate through a list can lead to errors if the list is modified during iteration, as the index will no longer be valid. Iterating using a variable for each element is safer and more Pythonic.

  1. Can I use for loops to iterate through other data structures like sets or tuples?

Yes, you can use for loops to iterate through sets and tuples in the same way as lists:

my_set = {"apple", "banana", "orange"}
for fruit in my_set:
print(fruit)
my_tuple = ("apple", "banana", "orange")
for fruit in my_tuple:
print(fruit)
  1. Why should I be careful when modifying mutable data types during iteration?

Modifying mutable data types during iteration can lead to unexpected results, such as the order of elements being changed or the loop not behaving as expected. To avoid these issues, it's best to create a copy of the mutable object before iterating over it or modify the original object outside the loop.

  1. What is the difference between enumerate() and using an index to iterate through a list?

enumerate() returns both the current element and its index, making it easier to keep track of the position in the list while iterating. Using an index directly can lead to errors if the list is modified during iteration.

  1. What happens when I try to modify a dictionary containing mutable data types during iteration?

Modifying a dictionary containing mutable data types (e.g., lists or dictionaries) during iteration can lead to unexpected results, such as the order of key-value pairs being changed or the loop not behaving as expected. To avoid these issues, it's best to create a copy of the mutable object before iterating over it or modify the original object outside the loop.

  1. What is the difference between items(), keys(), and values() methods in dictionaries?

The items() method returns a list of key-value pairs, keys() returns a list of keys, and values() returns a list of values from the dictionary. These methods are useful when iterating through dictionaries or performing operations on them.

Object Iterations (Python Programming) | Python | XQA Learn