w3resource
w3resource logo

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:

[フレーム]

PREV : issubclass()
NEXT : len()

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /