Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

for elt in itertools.chain.from_iterable(node):  if elt is the last element:   do statement 

How do I achieve this

like image 666
Bruce Avatar asked Jan 13 '10 17:01

Bruce


People also ask

How do you check if an object is an iterator in Python?

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.

What does ITER function do in Python?

The iter() function returns an iterator object.

What is Islice in Python?

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.


2 Answers

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 >>>  
like image 141
Steven Kryskalla Avatar answered Oct 06 '22 22:10

Steven Kryskalla


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 
like image 28
Chris Lutz Avatar answered Oct 06 '22 22:10

Chris Lutz