Iterating through sequences like lists, strings, and tuples is a common task in Python programming. The for
loop provides a simple and flexible way to iterate through the elements of these sequences and perform operations on each element.
In this comprehensive guide, we will cover everything you need to know about iterating through lists, strings, and tuples using for
loops in Python.
Table of Contents
Open Table of Contents
Overview of For Loops
A for
loop allows you to iterate through a sequence and execute a block of code for each element in the sequence. The basic syntax is:
for element in sequence:
# code block
element
is the variable that represents each element in the sequence during each iteration.sequence
is the list, string, tuple, etc. through which we want to iterate.
Let’s look at a simple example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This loops through the fruits list and prints each fruit name one by one.
The key thing to understand is that the for
loop iterates through all the elements of the sequence, assigning each one by one to the loop variable fruit
. We can then operate on fruit inside the loop body.
When the loop finishes iterating through all the elements, the execution moves to the next line after the for
loop body.
Iterating Through Lists
Lists are one of the most commonly used data structures in Python. Let’s go through some examples to understand how to iterate through lists using for
loops.
Simple Iteration
The basic way is to loop through all elements as seen earlier:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This prints each number in a new line.
We can also perform operations on the elements:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
squared = num * num
print(squared)
This prints the square of each number.
Using List Indices
We can also iterate through lists by index using the range()
function and len()
:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
num = numbers[i]
squared = num * num
print(squared)
This loops from 0 to the length of the numbers list, gets the number at each index, squares it, and prints it.
Iterating Multiple Lists Simultaneously
We can iterate through multiple lists simultaneously using zip():
names = ['John', 'Mary', 'Bob']
ages = [25, 30, 40]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
zip() zips the lists together into pairs, allowing us to iterate through them together.
Iterating in Reverse
To iterate through a list in reverse order, we can combine range() and len() with a negative step:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers) - 1, -1, -1):
print(numbers[i])
This loops from end to beginning of the list and prints the numbers in reverse order.
Looping While Modifying List
When modifying a list while iterating through it, it is safer to loop over a copy of the list:
numbers = [1, 2, 3, 4, 5]
copy_numbers = numbers[:]
for num in copy_numbers:
if num % 2 == 0:
copy_numbers.remove(num)
print(copy_numbers)
This iterates over a copy of the numbers list and removes even numbers from it. The original numbers list remains unaffected.
Early Exit from Loop
We can use break
to exit a for loop early:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
print("Found 3!")
break
print(num)
This loops through numbers, prints each number, and exits the loop once 3 is encountered.
Skipping Iterations
To skip certain iterations, we can use continue
:
for i in range(10):
if i % 2 == 0:
continue
print(i)
This prints only odd numbers between 0 to 10, skipping even numbers.
Nested Loops
We can have nested for
loops to iterate through multidimensional sequences:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for elem in row:
print(elem)
The outer loop iterates through each nested list row, and the inner loop prints each element in that row.
Iterating Through Strings
Strings are sequences of characters in Python. Let’s look at how to loop through them.
Simple Iteration
We can iterate through each character of a string using a for
loop:
name = "John"
for char in name:
print(char)
This loops through each character of the string and prints it.
Alternative with Indices
We can also iterate through string indices just like lists:
name = "John"
for i in range(len(name)):
print(name[i])
This achieves the same result, printing each character on a new line.
Operations on Characters
We can perform operations or transformations on characters inside the loop:
name = "John"
for char in name:
print(char.upper())
This converts each character to uppercase before printing.
String Slicing
We can also iterate through slices or portions of a string:
name = "John Doe"
for char in name[0:4]:
print(char)
This prints only the first 4 characters of the string.
Early Exit and Skipping
break
and continue
work in string iteration as well:
name = "John"
for char in name:
if char == 'h':
break
print(char)
for char in name:
if char in 'aeiou':
continue
print(char)
The first loop breaks early once ‘h’ is encountered, while the second loop skips vowels.
Iterating Through Tuples
Tuples are immutable sequences in Python. Iterating through tuples works exactly like lists:
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
This simple loops through the tuple and prints each element.
All the concepts we saw like indices, slicing, break
, continue
, etc. can be used on tuples as well since indexing and slicing works the same way.
The only difference is that tuples are immutable, so we cannot modify them while iterating unlike lists.
Common Iteration Operations
Let’s look at some common operations performed during iteration through sequences:
Summation
We can calculate the total sum of numbers in a list:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(total)
Average
Similar to summation, we can calculate average:
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
sum += num
average = sum / len(numbers)
print(average)
Finding min/max
We can track the minimum and maximum values during iteration:
numbers = [3, 8, 2, 5, 10]
minimum = numbers[0]
maximum = numbers[0]
for num in numbers:
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print(minimum, maximum)
Counting occurrences
We can count how many times an element occurs in a list:
numbers = [1, 2, 3, 4, 1, 2, 3, 1]
count = 0
for num in numbers:
if num == 1:
count += 1
print(count)
This counts how many 1s are present.
Filtering
We can filter out elements from a list that don’t satisfy a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
This iterates through numbers, adds the even ones to a new list, and prints it.
Advanced Iteration Functions
Python also provides some useful built-in functions and methods that simplify iteration:
range()
The range()
function can be used to generate indices to iterate through instead of directly using a list:
for i in range(5):
print(i)
This prints numbers 0 to 4.
We can also specify start, stop and step size:
for i in range(3, 8, 2):
print(i)
This prints odd numbers from 3 to 7.
enumerate()
The enumerate()
function adds a counter while iterating through a sequence:
names = ['John', 'Mary', 'Bob']
for counter, name in enumerate(names):
print(counter, name)
This prints the index and element during iteration.
zip()
As seen before, zip()
zips multiple sequences together into tuples:
colors = ['red', 'green', 'blue']
values = [255, 0, 0]
for color, value in zip(colors, values):
print(color, '=', value)
This zips the lists into tuple pairs.
reversed()
The reversed()
function reverses a sequence during iteration:
for num in reversed(range(5)):
print(num)
This loops from 4 to 0 instead of 0 to 4.
sorted()
sorted()
temporarily sorts a sequence while iterating:
colors = ['red', 'green', 'blue']
for color in sorted(colors):
print(color)
This iterates through the sorted colors list, without actually sorting the original list.
min(), max()
min()
and max()
can be used to get minimum and maximum values from a sequence:
numbers = [3, 8, 1, 5, 10]
print(min(numbers)) # Prints 1
print(max(numbers)) # Prints 10
Conclusion
Iterating through sequences like lists, tuples, and strings using for
loops is a fundamental concept in Python. This guide covered various ways to iterate through them and perform different operations on each element.
The key takeaways are:
- Use
for element in sequence
to iterate through any sequence. - We can loop through list indices using
range(len(sequence))
- zip() and enumerate() provide useful iteration functions
break
andcontinue
allow early exit and skipping iterations- Built-ins like min(), max(), reversed() provide advanced functionalities
- Strings and tuples can be iterated similarly to lists
For loops provide a powerful and efficient way to process and manipulate data in Python. Whether it is calculating statistics, filtering elements, or modifying sequences, for
loops lend themselves well to a wide range of common programming tasks involving iteration.
Mastering iteration through sequences will build a strong foundation for solving various problems and designing algorithms using Python.