89DEVs

Python iter() function

overview of iter()

The iter() function returns an iterator for the given object. It can be used to iterate through it one element at a time using the next() function.

example of iter()

The iter() function can be used in combination with the next() function to get all elements in the iterator object. # example of iter() letters = ['a', 'b', 'c', 'd', 'e'] lettersIter = iter(letters) print(next(lettersIter)) print(next(lettersIter)) print(next(lettersIter)) print(next(lettersIter)) print(next(lettersIter)) print(next(lettersIter)) The next() function returns the next letter in the iterator object five times. The last call results in a StopIteration Error, because there is no next element. a b c d e StopIteration

syntax of iter()

The syntax of the iter() function is: iter(object[, sentinel])

arguments of iter()

The iter() function accepts two arguments: The first argument is the object from which the iterator is to be created and it is required to pass this argument. The second argument is a special value that is used to represent the end of the sequence and this argument is optional.

return values of iter()

The iter() function returns an iterator object for the given object.

                
        

Summary


Click to jump to section