Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding range in python for loop

Tags:

python

The program below is finding prime numbers in a given range. for the noprimes list comprehension part, why do we have 3 parameters in range?

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]
print prime

and what is i doing there?

like image 354
Varun Avatar asked Sep 08 '26 15:09

Varun


1 Answers

See the docs:

range([start], stop[, step])

When comparing it to a for(..; ..; ..) loop e.g. in C the three arguments are used like this:

for(int i = start; i != stop; i += step)

There are also good examples in the docs:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
like image 147
ThiefMaster Avatar answered Sep 11 '26 05:09

ThiefMaster