w3resource

Python: iter() function

iter() function

The iter() function returns an iterator object.

Version:

(Python 3.2.5)

Syntax:

iter(object[, sentinel])

Parameter:

Name Description Required /
Optional
object An object whose iterator has to be created (can be sets, tuples, etc.) Required
sentinel special value that is used to represent the end of a sequence Optional

The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

Example: Python: iter() function

# list of letters
letters = ['P', 'y', 't', 'h', 'o', 'n']

lettersIter = iter(letters)

# prints 'P'
print(next(lettersIter))

# prints 'y'
print(next(lettersIter))

# prints 't'
print(next(lettersIter))

# prints 'h'
print(next(lettersIter))

# prints 'o'
print(next(lettersIter))

# prints 'n'
print(next(lettersIter))

Output:

P
y
t
h
o
n

Pictorial Presentation:

Python: Built-in-function - iter() function

Pictorial Presentation:

Python: Built-in-function - iter() function

Python Code Editor:

Previous: issubclass()
Next: len()

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.