How to use Python iter() function
In this article, we will learn how iterator works and how you can build your own iterator using iter() function in Python.
Introduction of Python Iterators
iter() function is used for creating objects which can be iterated every time.
iter() uses next() for accessing values.Iterator also makes our code look cool.
Examples of using iter() function in Python
Here are some of the examples of iter() function. We will implement this function on the list and tuple.
Use iter() on list
l=[1,2,3,4,5] # convert this list to iterable iterator l=iter(l) # Now using next(iterator) we can iterate every element in given list print(next(l)) print(next(l)) print(next(l)) print(next(l)) print(next(l))
1 2 3 4 5
Using iter() on tuple
# Creating a tuple having values in string web=("code","speedy","provides","good","articles") values=iter(web) # Now values uses iterable iterator on given list named web # Now using next() we can iterate every token of given list for in range(5): print(next(values)) # printing token of given list
code speedy provides good articles
Let’s Implement a program using iterators. The iterator you can see below will return all the odd numbers.
class InfiniteOddIterator: #Infinite iterator to return all odd numbers def __iter__(self): self.num = 1 return self def __next__(self): num = self.num self.num += 2 return num
We have created the class now let’s make its object and calling it.
object = iter(InfiniteOddIterator())
>>> next(object) next(object) 1 >>> next(object) next(object) 3 >>> next(object) next(object) 5 >>> next(object) next(object) 7 >>> next(object) next(object) 9
1 3 5 7 9
In this program, we could get all the odd numbers without storing the entire number system in memory. We can have infinite items in finite memory.
I hope you found this article helpful How to use iter() in Python.