Python Forum
One-time actions when iterating
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
One-time actions when iterating
#1
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.
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help with accessing .txt file and performing actions SamWestlakeCann 4 302 Mar-07-2024, 07:33 PM
Last Post: deanhystad
Question Timing actions with Python dangermaus33 0 981 Apr-19-2022, 10:08 PM
Last Post: dangermaus33
  Loop different actions for an array Tibovdv 4 2,704 Mar-25-2021, 06:46 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020