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.