Computer >> Computer tutorials >  >> Programming >> Python

Python - iter() method


Python inter() basically creates an iterator object, which can be used to iterate on iterables. Let's try to understand what it is iterator and iterables. Iterator − An iterator is an object that contains a countable number of values which can be iterated on iterables. Iterables: An iterables is basically a collections of data types such as list, tuple or string.

Syntax: iter()

iter(object, sentinel)

object − Required. An iterable object

sentinel − Optional. If the object is a callable object the iteration will stop when the returned value is the same as the sentinel

The iterator object uses the __next__() method. Every time it is called, the next element in the iterator stream is returned.

Example

list1 =[10, 20]
valuesL1 = iter(list1)
valuesL1.__next__()
//10
valuesL1.__next__()
//20

next() Calling __next__() method everytime is tedioud, so we will be using built-in function next() which accepts an iterato r object as a parameter and calls the __next__() method internally. This next() can be used instead of __next__()

Example

list1 =[10, 20]
valuesL1 = iter(list1)
next(valuesL1)
//10
next(valuesL1)
//20