geo197
geo197

Reputation: 13

Python: How to replace an if statement that is always true or false, inside a for loop?

I have a for loop like the following:

flag = True
for i in range(100000):
    if flag:
        foo()
    else:
        bar()

The flag variable is set by a command line argument and stays the same for every loop. Is there any way to get rid of the costly if statement, other than having 2 different for loops? Thanks in advance.

Upvotes: 1

Views: 878

Answers (1)

pistache
pistache

Reputation: 6203

flag = True
func = foo if flag else bar

for i in range(100000):
    func()

Upvotes: 1

Related Questions