Python Forum

Full Version: loop of two or three
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if i need to run a short little loop of just a constant two or three steps, which is preferred?

for x in range(2):
    print(f'this is step {x}')
    ...
or

for x in (0,1):
    print(f'this is step {x}')
    ....
the above are examples for a loop of two steps. a like question is presented for a loop of three steps. IOW, should we always use range() for constant loops even for short loops like two or three? or can we use literal tuples in these short cases? this question is about what is preferred by others than about language rules or requirements. this could refer to coding style requirements or just coding pythonic.

or, what is you preference?
I would definitely prefer the first one. It's more clear and explicit (given the purpose). Also the consistency - if you have to loop more fixed number of times I get you will use the range, i.e. you will not do for x in (0, 1, 2, 3, 4, 5), then why do it for 2 or 3 iterations?
It's also easier to change if you needed to.