By default, the range() function returns a list of numbers incremented by 1. Is it possible to have the numbers increment by another value?
Answer
The range() function can be provided with three parameters. The first parameter is the starting number for the list. The second is the end value for the list (the list will stop before this number). The final value is the value used for the increment. By default, the value is 1 but it can be changed to any number greater than 0.
The following examples show two ranges - one where the numbers are incremented by 2 and the other incremented by 5.
The above will give us an empty range ([]). There is nothing syntactically incorrect so it won’t raise an error, although it won’t make much sense.
range(start_value, end_value, stride)
When one of the index values is missing, the range function will not recognize the stride. Also, the end_value is exclusive, meaning not included in generated range.
Hey,
just fyi - range() in Python 2+ created a list object
xrange() - was just pure generator, which corresponds to range() function in Python3+
So just to finalize - range() in Python3 is a generator function which just reserves the instruction of how to pull integer links into object. You can iterate through range() to put values into list,array,dictionary,tuple,set u name it.
P.S. I am pretty sure my info is valid, but I study programming in General and Python for only 6 weeks so far, so I wouldn’t mind corrections or advices
My problem - I typed decimal number as a third argument in range() function, but at compilation, python interpreter reported an error which say,
“TypeError: ‘float’ object cannot be interpreted as an integer”
so i wanted to know that how can we get a list which can generate decimal number series like - 0.0, 0.2, 0.4, 0.6 …etc
That’s a good question, and not hard to answer. We can fashion our sequence from a range. Notice that your increments are 0.2. If we multiply that by 10, we get 2.
We may not have learned iterators at this point so lets build a function to return the sequence you want.
>>> def decimal_seq(diff, upper):
if diff <= 0 or diff >= 1: raise ValueError
d = int(diff * 10)
r = range(0, upper + 1, d)
s = []
for x in r:
s.append(x / 10)
return s
>>> dec = decimal_seq(0.2, 20)
>>> dec
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
>>>
We can simplify this with an iterator, but why race ahead. Let’s think in naive terms for a little while longer so we get the practice working with loops.