Skip to content
Advertisement

Python How to I check if last element has been reached in iterator tool chain?

for elt in itertools.chain.from_iterable(node):

if elt is the last element:
  do statement

How do I achieve this

Advertisement

Answer

When the loop ends, the elt variable doesn’t go out of scope, and still holds the last value given to it by the loop. So you could just put the code at the end of the loop and operate on the elt variable. It’s not terribly pretty, but Python’s scoping rules aren’t pretty either.

The only problem with this (thanks, cvondrick) is that the loop might never execute, which would mean that elt doesn’t exist – we’d get a NameError. So the full way to do it would be roughly:

del elt # not necessary if we haven't use elt before, but just in case
for elt in itertools.chain.from_iterable(node):
    do_stuff_to_each(elt)
try:
    do_stuff_to_last(elt)
except NameError: # no last elt to do stuff to
    pass
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement