for elt in itertools.chain.from_iterable(node): if elt is the last element: do statement
How do I achieve this
To check if the object is iterable in Python, use the iter() method. Python iter() is an inbuilt function that returns an iterator for the given object. The iter() method is the most accurate way to check whether an object is iterable and handle a TypeError exception if it isn't.
The iter() function returns an iterator object.
islice() - The islice() function allows the user to loop through an iterable with a start and stop , and returns a generator. map() - The map() function creates an iterable map object that applies a specified transformation to every element in a chosen iterable.
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 >>>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With