Python Forum
loop of two or three - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: loop of two or three (/thread-25607.html)



loop of two or three - Skaperen - Apr-05-2020

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?


RE: loop of two or three - buran - Apr-05-2020

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?


RE: loop of two or three - ndc85430 - Apr-05-2020

It's also easier to change if you needed to.