Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop of two or three
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
It's also easier to change if you needed to.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020