Iterators, `iter`, and `next` [ref]
Problem
- Obtain both values from an iterator over
[10, 20].
- Read a default value after that iterator is exhausted.
- Consume an iterator over
[1, 2] twice with list.
- Lazily map
int across ["1", "2"], then consume the result.
- Catch
StopIteration from an empty iterator.
Python solution
it = iter([10, 20])
next(it) # 10
next(it) # 20
next(it, "done") # 'done'
it = iter([1, 2])
list(it) # [1, 2]
list(it) # []
values = map(int, ["1", "2"])
list(values) # [1, 2]
try:
next(iter([]))
except StopIteration:
exhausted = True
exhausted # True
Links