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



Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9