I am trying to iterate through a list, and I need to perform a certain operation when and only when the iteration has reached the end of the list, see the example below:
data = [1, 2, 3] data_iter = data.__iter__() try: while True: item = data_iter.next() try: do_stuff(item) break # we just need to do stuff with the first successful item except: handle_errors(item) # in case of no success, handle and skip to next item except StopIteration: raise Exception("All items weren't successful")
I believe this code is not too Pythonic, so I'm looking for a better way. I think the ideal code should look like this:
data = [1, 2, 3] for item in data: try: do_stuff(item) break # we just need to do stuff with the first successful item except: handle_errors(item) # in case of no success, handle and skip to next item finally: raise Exception("All items weren't successful")
Any thoughts are welcome.
python iterator list stopiteration
Serge Tarkovski
source share