![]() |
One-time actions when iterating - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: One-time actions when iterating (/thread-26191.html) |
One-time actions when iterating - ClassicalSoul - Apr-23-2020 Please note I've made a substantive edit to my original post Suppose you had the following code, where x is an iterable:for i in x: # do thing 1 # do thing 2 if <condition>: # do thing 3 # do thing 4 continueBut after the condition is met the first time you no longer wish to do thing 4. We could try: x_iter = iter(x) for i in x: # do thing 1 # do thing 2 if <condition>: # do thing 3 # do thing 4 break for i in x: # do thing 1 # do thing 2 if <condition>: # do thing 3But of course we would be repeating code. My question is whether there some shortcut to what I do in the second example. RE: One-time actions when iterating - bowlofred - Apr-23-2020 Is there a reason you wouldn't just add another conditional? thing_4_done = False for i in x: # do thing 1 # do thing 2 if <condition>: # do thing 3 if not thing_4_done: # do thing 4 first time condition is met thing_4_done = True |