Python Forum

Full Version: One-time actions when iterating
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
        continue
But 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 3
But of course we would be repeating code. My question is whether there some shortcut to what I do in the second example.
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