Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally entering a for loop

What is a way to avoid code repetition to loop if argument is a sequence (list, tuple) or to skip the loop but execute the action just once?

def foo(arg1,sequence=None):
    # If possible, loop, else do it once
        if isinstance(sequence,(list,tuple)):
            for value in sequence:
                do_something(arg1)
        else:
            do_something(arg1)

The actions I do in the for loop are way longer than this, and I was wondering what approach you normally use to avoid this, if you do avoid it. I often come across this issue and I haven't come up with something to 'solve' it.

EDIT: Question is not a duplicate of In Python, how do I determine if an object is iterable?, as suggested. I do not want to introduce a different condition. I want to avoid the repetition.

like image 492
cap Avatar asked Jan 29 '26 13:01

cap


1 Answers

Standardise on the loop being the default case and transform your single case into an iterable:

if not isinstance(sequence, (list, tuple)):
    sequence = [sequence]

for value in sequence:
    do_something(value)
like image 115
deceze Avatar answered Jan 31 '26 02:01

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!