Dup Ver Goto 📝

Consuming in a For Loop

To
31 lines, 117 words, 610 chars Page 'GobbleIterator' does not exist.
# How to consume parts of the input using for in
# we use iter() to make an interator out of the source
# and then we can use next() to get and consume
# we need to catch StopIteration

seq = list(range(10))

seq_iterator = iter(seq)
for x in seq_iterator:
  if x == 5:
    y = next(seq_iterator)
    print(f"Gobbled {y} at {x}")
  else:
    print(f"Normal {x}")

output = """
Normal 0
Normal 1
Normal 2
Normal 3
Normal 4
Gobbled 6 at 5
Normal 7
Normal 8
Normal 9
"""
# note that the for loop doesn't see the element 6
# this is handy when parsing command line args where
# some args take a parameter