Looping range based on condition

I want to say something like:

if switch == True:
    for i in range(5):
        # stuff()
else:
    for i in range(10):
        # stuff()

Is there a more Pythonic way for this?

Upvotes: 0

Views: 94

Answers (2)

alecxe
alecxe

Reputation: 473823

Use an inline short form of if/else:

for i in range(5 if switch else 10):
    # stuff()

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121484

Combine it in one with a conditional expression:

for i in range(5 if switch else 10):
    # do something with i

You don't need to test for == True here; if already does this for you.

A little more readable would be to separate out the end value into a variable:

end = 5 if switch else 10
for i in range(end):
    # do something with i

Upvotes: 8

Related Questions