Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's `range` function with 3 parameters

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

like image 417
user2537522 Avatar asked Aug 19 '15 13:08

user2537522


People also ask

Can range function have 3 arguments?

The range function takes one or at most three arguments, namely the start and a stop value along with a step size.

What are the 3 parameters of range function?

in the above code, range has 3 parameters : Start of Range (inclusive) End of Range (Exclusive) Incremental value.

What does the third parameter mean in a range () function in Python?

The 3rd argument of range is the stepping, meaning how much to increment the last value for: >>> for i in range (0,10,2): ... print i 0 2 4 6 8.

How many parameters does range take Python?

The range() is an in-built function in Python. It returns a sequence of numbers starting from zero and increment by 1 by default and stops before the given number. It has three parameters, in which two are optional: start: It's an optional parameter used to define the starting point of the sequence.


1 Answers

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)
}
like image 132
Vijendran Selvarajah Avatar answered Sep 25 '22 14:09

Vijendran Selvarajah