Table of Contents | |
Understanding Python iter()
Function
The iter()
function is a fundamental part of working with iterators. It is used to obtain an iterator from an object. An iterator is an object that allows you to traverse through a sequence of values one at a time. Python iter() either takes a single argument, which should be an iterable object (like a list, tuple, or string), or it takes two arguments: a callable object and a sentinel value.
Syntax of Python iter()
iterator_object = iter(iterable)
# OR
iterator_object = iter(callable, sentinel)
Explanation
iterator_object
: This variable will hold the iterator.iter()
: Built-in function to get an iterator.iterable
: Object that supports iteration (e.g., list, tuple, string).callable
: A function or other callable object (in the two-argument form).sentinel
: A value that signals the end of iteration (in the two-argument form).
Example of Python iter()
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
Explanation
my_list = [1, 2, 3]
: Creates a list.my_iterator = iter(my_list)
: Gets iterator from the list.print(next(my_iterator))
: Gets and prints the next item (1).print(next(my_iterator))
: Gets and prints the next item (2).
Output
1
2
iter()
Parameters
Python iter() function has two distinct forms, each with different parameters. The first form takes a single parameter, an object, which must be iterable (something that supports iteration, like a list, tuple, string, set, or a custom object that implements the iterator protocol). Iter()
takes two parameters in the second form: callable and sentinel. The callable must be a callable object (usually a function) that takes no arguments. The sentinel is a specific value; when callable returns this sentinel value, iteration stops.
Syntax
# Single-argument form
iterator = iter(iterable_object)
# Two-argument form
iterator = iter(callable_object, sentinel_value)
Explanation
iterator
: Stores the resulting iterator object.iter()
: Obtains the iterator.iterable_object
: Must support iteration (single-argument form).callable_object
: A function or callable (two-argument form).sentinel_value
: Value that stops iteration (two-argument form).
Example
# Two-argument form example
class Counter:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __call__(self):
if self.current < self.limit:
self.current += 1
return self.current
else:
return -1 # Sentinel value
counter = Counter(3)
counter_iter = iter(counter, -1)
for val in counter_iter:
print(val)
Explanation
class Counter:
: Creates a custom class.def __init__(self, limit):
: Constructor.self.limit = limit
andself.current = 0
: Initializes attributes.def __call__(self):
: Makes instances callable.if self.current < self.limit:
: Checks current value is smaller than limit.self.current += 1
andreturn self.current
: Increment and return if smaller than limit.return -1
: Sentinel value to stop.counter = Counter(3)
: Creates object.counter_iter = iter(counter, -1)
: Creates iterator using two-argument form.for val in counter_iter:
: Iterate and print the value.
Output
1
2
3
iter()
Return Value
Python iter() function always returns an iterator object. This iterator is what you use to step through the values one by one, typically using the next()
function. If you call iter()
on an object that is not iterable (in the single-argument form) and does not have __iter__
method, you’ll get a TypeError. In the two-argument form, the iterator keeps calling the callable object until it returns the sentinel value.
Syntax
iterator = iter(something)
Explanation
iterator
: Stores the returned iterator.iter()
: Creates or obtains iterator.something
: Either iterable or a callable and sentinel pair.
Example
my_string = "abc"
string_iterator = iter(my_string)
print(type(string_iterator))
Explanation
my_string = "abc"
: Creates a string (which is iterable).string_iterator = iter(my_string)
: Gets an iterator for the string.print(type(string_iterator))
: Prints the type of the iterator.
Output
<class ‘str_iterator’>
Python iter()
for custom objects
You can make your classes iterable by implementing the iterator protocol. This involves defining two special methods: __iter__()
and __next__()
. The __iter__()
method should return the iterator object (usually self), and the __next__()
method should return the next value in the sequence. When no more values exist, __next__()
should raise the StopIteration exception. When you call Python iter() on an instance of such a class, it automatically calls the __iter__()
method.
Syntax
class MyIterable:
def __iter__(self):
# Return the iterator object (usually self)
pass
def __next__(self):
# Return the next value, or raise StopIteration
pass
Explanation
class MyIterable
: Defines a custom iterable class.def __iter__(self):
: Returns the iterator object.pass
: Placeholder for__iter__
implementation.def __next__(self):
: Returns the next value or raisesStopIteration
.pass
: Placeholder for__next__
implementation.
Example
class MySequence:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
value = self.data[self.index]
self.index += 1
return value
else:
raise StopIteration
my_seq = MySequence([4, 5, 6])
my_iter = iter(my_seq)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
Explanation
class MySequence:
: Defines custom class.def __init__(self, data):
: Initializer.self.data = data
: Stores data in the instance.self.index = 0
: Initializes an index for iteration.def __iter__(self):
: Makes the class iterable.return self
: Return the object itself.def __next__(self):
: Defines how to get the next item.if self.index < len(self.data):
: Check the index is within bounds.value = self.data[self.index]
: Retrieves value at current index.self.index += 1
: Increases the index.return value
: Returns the value.raise StopIteration
: Signals end of iteration.my_seq = MySequence([4, 5, 6])
: Creates aMySequence
object.my_iter = iter(my_seq)
: Gets an iterator frommy_seq
.print(next(my_iter))
: Prints next value.print(next(my_iter))
: Prints next value.print(next(my_iter))
: Prints next value.
Output
4
5
6
Python iter()
with Sentinel Parameter
The two-argument form of Python iter() provides a powerful way to create iterators from callable objects (like functions). In this form, iter(callable, sentinel), the callable is called repeatedly without arguments. Each time the callable returns a value, the iterator yields that value. When the callable returns the sentinel value, the iteration stops (a StopIteration exception is raised internally, ending the loop).
Syntax
iterator = iter(callable_object, sentinel_value)
Explanation
iterator
: Variable that will hold iterator.iter()
: Creates iterator with a callable and a sentinel.callable_object
: A function (or other callable) that takes no arguments.sentinel_value
: Iteration stops whencallable_object
returns this value.
Example
import random
def random_until_five():
return random.randint(1, 10)
random_iter = iter(random_until_five, 5)
for num in random_iter:
print(num)
Explanation
import random
: Importsrandom
module.def random_until_five():
: Function that returns random integer between 1 and 10.return random.randint(1, 10)
: Generates a random number.random_iter = iter(random_until_five, 5)
: Creates an iterator which calls random function until 5 returned.for num in random_iter:
: Loops through the iterator.print(num)
: Prints values.
Output
8
1
10
6
9
2
Python iter()
with Callable
Using the callable parameter of the iter()
function, the function continuously calls the method and returns the value until the sentinel value matches.
Syntax
iterator = iter(callable, sentinel)
Explanation
iterator
: Variable which holds iterator.iter()
: Method to get the iterator.callable
: Method or object which needed to be called.sentinel
: Value, whencallable
returns this value, the loop will be terminated.
Example
class MyCounter:
def __init__(self, limit):
self.current_value = 0
self.limit = limit
def __call__(self):
if(self.current_value < self.limit):
self.current_value += 1
return self.current_value
return -1
my_counter = MyCounter(5)
for i in iter(my_counter, -1):
print (i)
Explanation
class MyCounter
: Creates a custom class.def __init__(self, limit)
: Constructor to initilize instance variable.self.current_value = 0
andself.limit = limit
: Assign default values.def __call__(self):
: Method to make the class instance callable.if(self.current_value < self.limit):
: Check current value.self.current_value += 1
: Increment the value.return self.current_value
: Return incremented value.return -1
: Return sentinel value.my_counter = MyCounter(5)
: Creates an instance of the class.for i in iter(my_counter, -1):
: Calls iter method.print(i)
: Prints the returned value.
Output
1
2
3
4
5
Python iter()
with Dictionary
When you use the iter()
with a dictionary, it returns iterator of the keys.
Syntax
dictionary_iterator = iter(dictionary)
Explanation
dictionary_iterator
: Variable to hold returned iterator.iter()
: To get the iterator.dictionary
: The dictionary object.
Example
dictionary = {"a":1, "b":2, "c":3}
for key in iter(dictionary):
print(key)
Explanation
dictionary = {"a":1, "b":2, "c":3}
: Define dictionary.for key in iter(dictionary):
: Iterate through the keys of the dictionary.print(key)
: Prints the current key.
Output
a
b
c
Python iter()
with List
When you use iter()
with a list, it returns iterator of the list elements.
Syntax
list_iterator = iter(list)
Explanation
list_iterator
: Variable to hold the iterator.iter()
: To get the iterator.list
: List variable.
Example
list1 = [1,2,3]
for element in iter(list1):
print(element)
Explanation
list1 = [1,2,3]
: Initialize list.for element in iter(list1):
: Get the iterator and iterate through it.print(element)
: Prints the current element.
Output
1
2
3
Python iter()
with Tuple
You can use iter()
method with Tuple. It will return the iterator of the tuple elements.
Syntax
tuple_iterator = iter(tuple)
Explanation
tuple_iterator
: Variable to store returned iterator.iter()
: To get the iterator.tuple
: Tuple variable.
Example
tuple1 = (4,5,6)
iterator = iter(tuple1)
print (next(iterator))
print (next(iterator))
print (next(iterator))
Explanation
tuple1 = (4,5,6)
: Assign tuple.iterator = iter(tuple1)
: Get iterator from the tuple.print (next(iterator))
: Prints the first element usingnext()
.print (next(iterator))
: Prints the second element.print (next(iterator))
: Prints the third element.
Output
4
5
6
Conclusion
Python iter() function is used to get an iterator from an object. iter()
can take either one or two arguments. In the one-argument form, it takes an iterable object and returns an iterator for that object. In the two-argument form, iter(callable, sentinel), it repeatedly calls the callable (without arguments) until the callable returns the sentinel value.