Search code examples
pythonpython-3.xfor-looppython-itertools

Iterator to reverse a for loop's order of execution?


I have been searching the docs for itertools, as well as SO for a while now and have not yet found what I'm looking for. I'm hoping to reverse the order of execution of a for loop so the following happens:

for letter in ["A","B","C"]:
    do_something(letter)
    do_something_else(letter)


def do_something(letter):
   print("do_something with " + letter)
 
def do_something_else(letter):
   print("do something_else with " + letter)

with the normal output of a for loop being:

do_something with A
do something_else with A
do_something with B
do something_else with B
do_something with C
do something_else with C

And I would like it (the iterator) to output like:

do_something with A
do_something with B
do_something with C
do something_else with A
do something_else with B
do something_else with C

I won't lie it's been a long day so the answer is probably right under my nose, the best I've come up with so far is:

for letter in ["A","B","C"]:
    do_something(letter)

for letter in ["A","B","C"]:
    do_something_else(letter)


def do_something(letter):
   print("do_something with " + letter)
 
def do_something_else(letter):
   print("do something_else with " + letter)

But that feels very clunky since I'm repeating the for loop. Any help is vastly appreciated. Thanks all!


Solution

  • Another option is an outer loop over the functions, and an inner loop over the letters.

    for f in [do_something, do_something_else]:
        for letter in ["A","B","C"]:
            f(letter)
    

    Yet, another alternative is to use itertools/product on the functions an inputs (output is as desired).

    from itertools import product
    
    for f, letter in product([do_something, do_something_else], ["A","B","C"]):
        f(letter)