for elt in itertools.chain.from_iterable(node):
if elt is the last element:
do statement
How do I achieve this
You can do this by manually advancing the iterator in a while loop using iter.next()
, then catching the StopIteration
exception:
>>> from itertools import chain
>>> it = chain([1,2,3],[4,5,6],[7,8,9])
>>> while True:
... try:
... elem = it.next()
... except StopIteration:
... print "Last element was:", elem, "... do something special now"
... break
... print "Got element:", elem
...
...
Got element: 1
Got element: 2
Got element: 3
Got element: 4
Got element: 5
Got element: 6
Got element: 7
Got element: 8
Got element: 9
Last element was: 9 ... do something special now
>>>