11
votes

I understand that the following line will give the given result:

for in range(5):
   print(i)

0 1 2 3 4

But I don't understand how if adding 3 separate parameters the result is confusing. How is this returning these particular results? (4 6 and 8) ????

for i in range(4, 10, 2):
 print(i) 

4 6 8

3
the last argument is the step so obviously using a step of 2 gives you 4,6,8 - Padraic Cunningham
I'm voting to close this question as off-topic because the docs: docs.python.org/2/tutorial/controlflow.html#the-range-function are clear - EdChum

3 Answers

23
votes

Starts at 4, then increments by 2, to end at 8 because 10 < 10 is false. So 4 6 8

6
votes
for i in range(4, 10, 2):
 print(i) 

in the above code, range has 3 parameters :

  1. Start of Range (inclusive)
  2. End of Range (Exclusive)
  3. Incremental value

For more clarity refer below for the java representation of above python code:

for (int i=0; i<10; i+=2){
    System.out.println(i)
}
2
votes

range(start_pos, end_pos, increment)