what if we use some math operations inside the range in for loop in python

Viewed 109

I am wondering, if we use

for n in range(500/2):

does it mean, that for each iteration, it each time solves 500/2 = 250? Or it just solves it once, and then uses it?

Or

x = 100
for n in range(x):

does it mean, that for each iteration, it each time refers to x Or it just takes its value once, and uses later on?

2 Answers

The expression inside the range() call is evaluated once and a range object is constructed. Then, you iterate over it, regardless of how it was constructed.

It is calculated only once, range() returns a sequence of numbers (once) which is used for iterating.

More about range() here for example.

Related