Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct coding for the range function

Tags:

python

range

While working on python I've seen 2 different ways to use the range function when we want to create the list starting from 0.

list=range(10)
list=range(0,10)

I know that if we change the 0 for another number the output is different, but in this case, the output is exactly the same.

I want to know if it's only a personal decision or is there something more meaningful to use one or the other syntax (memory, debugging, etc).

like image 783
Leon palafox Avatar asked Feb 16 '23 22:02

Leon palafox


2 Answers

There is nothing special about doing it the second way. One reason I can think of would be if you want the 0 to be a place-holder for something else - i.e. if you intend to change it to something else later on, and you include the 0 to indicate that. Other than that, it's simply preference. In my personal opinion, unless you have a good reason to include the 0, I would stick with range(10).

Just as a note, you should never use list as a variable name since it's a built-in function.

like image 117
arshajii Avatar answered Mar 25 '23 11:03

arshajii


The second example is a more explicit call of the range class. It explicitly defines the starting point. Similarly, you can explicitly define the 'step' of each iteration: range(0, 10, 2) ---> (0, 2, 4, 6, 8) (see help(range) in the python interpreter: which shows: class range(object) | range([start,] stop[, step]) where [start,] and [,step] are optional. As you have shown, range(x) will begin at 0, and step by 1 by default.

Since python 3, the range function is now the same as xrange() used to be, in that it iterates at each step, as opposed to creating a list.

like image 26
Nick Burns Avatar answered Mar 25 '23 10:03

Nick Burns