Python Iterators

An iterator is an object that contains a countable number of values. Iterators are used to iterate over iterable objects like lists, tuples, dictionaries, and sets.

Example 1: Using an Iterator

Create an iterator from a list and iterate through it using next().

# Using an iterator
names = ["Karthick AG", "Vijay", "John"]
name_iterator = iter(names)
print(next(name_iterator))
print(next(name_iterator))
print(next(name_iterator))

Karthick AG

Vijay

John

Example 2: Creating a Custom Iterator

Create an iterator that returns numbers starting from 1, and each sequence increases by one.

# Custom iterator class
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self
    def __next__(self):
        x = self.a
        self.a += 1
        return x

numbers = MyNumbers()
number_iterator = iter(numbers)
print(next(number_iterator))
print(next(number_iterator))
print(next(number_iterator))

1

2

3

Example 3: StopIteration

Stop the iteration after a specified number of iterations.

# Using StopIteration
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self
    def __next__(self):
        if self.a <= 5:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration

numbers = MyNumbers()
for num in numbers:
    print(num)

1

2

3

4

5

Example 4: Iterating Over a Dictionary

Use an iterator to loop through a dictionary's keys.

# Iterator over dictionary keys
freedom_fighters = {
    "Velu Nachiyar": "Sivaganga",
    "V. O. Chidambaram Pillai": "Ottapidaram"
}
iterator = iter(freedom_fighters)
print(next(iterator))
print(next(iterator))

Velu Nachiyar

V. O. Chidambaram Pillai

Example 5: Iterating Over a String

Iterate through the characters of a string using an iterator.

# Iterator over a string
language = "Tamil"
string_iterator = iter(language)
for letter in string_iterator:
    print(letter)

T

a

m

i

l

Example 6: Infinite Iterator

Create an iterator that generates an infinite sequence of numbers (use with caution).

# Infinite iterator
class InfiniteNumbers:
    def __iter__(self):
        self.a = 1
        return self
    def __next__(self):
        x = self.a
        self.a += 1
        return x

numbers = InfiniteNumbers()
number_iterator = iter(numbers)
print(next(number_iterator))
print(next(number_iterator))
# Continue as needed

Explanation: Iterators allow you to traverse through all the elements of a collection, regardless of its specific implementation. Custom iterators are defined using the __iter__() and __next__() methods.