Python Glossary Русский

all Python 3Built-in functionsterm

iter

iterators

Returns an iterator. With two arguments it calls the function until it returns the sentinel value.

Syntax

iter(object)
iter(callable, sentinel)

An iterator is single-use, and calling iter on an existing iterator gives back the same object — a second pass yields nothing, so build a fresh iterator from the original collection. The two-argument form calls the zero-argument callable over and over until it returns the sentinel, and the sentinel itself is not yielded. That turns a read-until-marker loop into a plain for loop instead of while True with a manual break.

Examples

it = iter([1,2,3])
print(next(it), next(it))  # → 1 2
it2 = iter('hello')
print(list(it2))  # → ['h','e','l','l','o']
# sentinel-вариант
from io import StringIO
f = StringIO('a\nb\nc')
for line in iter(f.readline, ''):
    print(line.strip())
print(list(iter(range(5))))  # → [0, 1, 2, 3, 4]
it = iter([1,2,3])
print(next(it))  # → 1
print(next(it))  # → 2
print(next(it))  # → 3
print(next(it, 'end'))  # → end
# iter со sentinel: вызывать, пока не вернёт ''
import io
f = io.StringIO('line1\nline2\n')
for line in iter(f.readline, ''):
    print(line.strip())  # → line1 / line2
for ch in iter('hello'):
    print(ch, end='')  # → hello
print()
print(next(iter([]), None))  # → None — default вместо StopIteration
# Бесконечный итератор + islice
from itertools import islice, count
it4 = count(1)
print(list(islice(it4, 5)))  # → [1,2,3,4,5]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy