Python: iter, enumerate, zip

Iteration involves looping over sequences of values, and Python provides several built-in methods to simplify this process. In this article, we’ll explore the concept of iterators and how to use built-in functions to make iteration over sequences quick and easy.

Rahul S


In Python, an iterator is an object that allows us to traverse through a sequence of values one at a time. It is a fundamental concept in Python programming and is used extensively when working with lists, strings, files, and more. Iterators are at the heart of for loops, allowing you to iterate over elements in a sequence efficiently.

The iter() Function

The iter() function is a built-in Python function that creates an iterable object from a sequence. You can use it to convert lists, strings, or other iterable objects into an iterator. Here's an example of how it works:

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
iterator = iter(days)

print(next(iterator)) # Output: Mon
print(next(iterator)) # Output: Tue
print(next(iterator)) # Output: Wed

In this example, we create an iterator from the list of days and use the next() function to retrieve the next item in the sequence.

Iterating Over Files with iter()

The iter() function can be particularly useful when processing files line by line. Let's say you have a text file with multiple lines, and you want to read and process each line. You can achieve this easily with iter():

with open("example.txt", "r") as file_pointer:
for line in iter(file_pointer.readline, ''):

In this code snippet, we open a file and use the iter() function with the readline() method as the source of values. We pass an empty string as the sentinel value to indicate the end of the file. This code reads and prints each line in the file until it reaches the end.

Tracking index of a sequence enumerate() Function