Loop through a list and handle StopIteration in Python beautifully

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.

+8
python iterator list stopiteration
source share
1 answer

You can use else after the for loop, and the code inside this else is executed only if you don't break out of the for loop:

 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 Exception: handle_errors(item) # in case of no success, handle and skip to next item else: raise Exception("All items weren't successful") 

This can be found in the documentation for the for statement , the relevant parts shown below:

 for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] 
Operator

A break , executed in the first batch, completes the loop without executing the else batch.

+16
source share

All Articles