Understanding Iteration in Python
What is Iteration?
Iteration in programming refers to the process of repeatedly executing a set of instructions or a block of code. In Python, iteration is a fundamental concept that allows you to work with sequences, such as lists, tuples, and strings, as well as other iterable objects.
Iterable Objects
An iterable object is an object that can be iterated over, meaning it can be looped through and its elements can be accessed one by one. In Python, common iterable objects include:
- Lists
- Tuples
- Strings
- Dictionaries
- Sets
- Files
- Custom objects that implement the iterator protocol
The for
Loop
The for
loop is the most common way to iterate over an iterable object in Python. The for
loop allows you to execute a block of code for each element in the iterable object.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
The while
Loop
The while
loop is another way to implement iteration in Python. The while
loop continues to execute a block of code as long as a specified condition is true.
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Iterators and the Iterator Protocol
Behind the scenes, the for
loop and other iteration mechanisms in Python use the iterator protocol. An iterator is an object that implements the iterator protocol, which defines two methods: __iter__()
and __next__()
. The __iter__()
method returns the iterator object itself, and the __next__()
method returns the next item in the sequence.
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
result = self.data[self.index]
self.index += 1
return result
else:
raise StopIteration()
my_iterator = MyIterator([1, 2, 3, 4, 5])
for item in my_iterator:
print(item)
Output:
1
2
3
4
5