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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With