Python Functions creating iterators for efficient looping



In this article, we will talk about creating iterators for efficient looping in Python functions. An iterator is something that helps you go through all the items one by one, like going through pages of a book one page at a time.

In Python, we can use lists, tuples, dictionaries, and sets as iterators. So we will explore Python functions that generate iterators for efficient looping.

Creating Iterators with Functions

Python provides different ways to create iterators using functions. So let us see some examples of creating iterators for efficient looping in Python functions -

Using Generator Functions

In Python, we can end a function halfway and continue later from where it stopped. This type of function is called a generator. It gives one value at a time, which saves memory and is useful for big data.

Example 

The following example will generate numbers from 1 to 3 with the help of yield. The yield statement is used to return a value and pause the function.

Open Compiler
# Create a generator function def gen_vals(): n = 1 while n <= 3: # Use yield to return a value yield n n += 1 # Use the generator function for v in gen_vals(): print(v)

Output

This will create the following outcome -

1
2
3

Using Generator Expressions

This is another way to create an iterator using a generator expression. A generator expression is just like a list comprehension but uses parentheses instead of square brackets. It generates values as needed.

Example 

Following is an example -

Open Compiler
# Creates squares of numbers using generator expression nums = (x**2 for x in range(1, 6)) # Loop through the generator expression for n in nums: print(n)

Output

This will generate the following result -

1
4
9
16
25

Using iter() Function

The iter() function in Python is used to create an iterator from an iterable object. An iterable is any Python object that can return its members one at a time means it allows you to loop over items in a for loop or comprehensions.

An iterator has two main functions, iter(), which is used to create the iterator, and next() used to get the next value. After the last item, if you call next() again, you get an error named StopIteration.

Example

Let us see a small example of the iter() function -

Open Compiler
my_list = [10, 20, 30] it = iter(my_list) print(next(it)) print(next(it)) print(next(it)) # Raises StopIteration error # print(next(it))

Output

Here is the output of the above example -

10
20
30

Using Custom Iterator Classes

You can also create your iterator by defining a class with the methods __iter__() and __next__(). The __iter__() method returns the iterator object itself, and the __next__() method returns the next value. If there are no more values, it will raise an error called StopIteration.

Example

Following is an example -

Open Compiler
# Define a custom iterator class class MyIterator: def __init__(self, start, end): self.current = start self.end = end def __iter__(self): return self def __next__(self): if self.current > self.end: raise StopIteration else: value = self.current self.current += 1 return value # Create an instance of MyIterator my_iter = MyIterator(1, 5) # Loop through the custom iterator for num in my_iter: print(num)

Output

This will lead to the following outcome -

1
2  
3
4
5

Using itertools Module

The itertools module in Python provides functions that create iterators for efficient looping. It has functions like count(), cycle(), and repeat() that can be used to create iterators.

Example

In our program, we are using the count() function from the itertools module to create an iterator that generates numbers from 1 and increments by 2 each time.

Open Compiler
# Import the itertools module import itertools # Create an iterator using itertools.count counter = itertools.count(start=1, step=2) # Loop through the iterator for _ in range(5): print(next(counter))

Output

The result of this Python program is -

1
3
5
7
9  
Updated on: 2025-06-10T19:01:35+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements