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


Messages In This Thread
One-time actions when iterating - by ClassicalSoul - Apr-23-2020, 04:40 PM
RE: One-time actions when iterating - by bowlofred - Apr-23-2020, 07:39 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  help with accessing .txt file and performing actions SamWestlakeCann 4 462 Mar-07-2024, 07:33 PM
Last Post: deanhystad
Question Timing actions with Python dangermaus33 0 1,044 Apr-19-2022, 10:08 PM
Last Post: dangermaus33
  Loop different actions for an array Tibovdv 4 2,835 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