Home >Backend Development >Python Tutorial >How to use the iter() function in Python to obtain the iterator of an iterable object
How to use the iter() function in Python to obtain the iterator of an iterable object
In Python, iteration is a very common programming operation. Through iteration operations, we can access the elements in an iterable object one by one. Iterable objects in Python include lists, tuples, strings, dictionaries, sets, etc. To implement iterative operations, we first need to obtain the iterator of the iterable object. The iter() function is used to obtain the iterator of an iterable object.
The iter() function is a built-in function in Python that returns an iterator object. An iterator is an object that can access elements one by one through the next() function. The iter() function has two main uses, namely passing in an iterable object and a callable object.
First, let’s look at the first usage, which is to pass in an iterable object. The following is an example:
num_list = [1, 2, 3, 4, 5] iter_obj = iter(num_list) print(next(iter_obj)) # 输出1 print(next(iter_obj)) # 输出2 print(next(iter_obj)) # 输出3 print(next(iter_obj)) # 输出4 print(next(iter_obj)) # 输出5
In this example, we first define a list num_list
, and then convert it into an iterator object iter_obj# through the iter() function ##. After that, we use the next() function to access the elements in
iter_obj one by one, and the output results are 1, 2, 3, 4, and 5.
import random class RandomNumberGenerator: def __iter__(self): return self def __next__(self): return random.randint(1, 10) rng = RandomNumberGenerator() iter_obj = iter(rng) print(next(iter_obj)) # 输出一个随机数 print(next(iter_obj)) # 输出另一个随机数 print(next(iter_obj)) # 又输出一个随机数In this example, we define a
RandomNumberGenerator class that implements
__iter__() and
__next__() method. The
__iter__() method returns
self, the iterator object itself, while the
__next__() method returns a random number each time it is called. Then, we created a
RandomNumberGenerator object
rng and passed it into the iter() function to obtain the iterator object
iter_obj. Finally, we use the next() function to access the elements in
iter_obj one by one, and the output result is a randomly generated value.
The above is the detailed content of How to use the iter() function in Python to obtain the iterator of an iterable object. For more information, please follow other related articles on the PHP Chinese website!