At first I thought range() generated a list. But the Python command line shows this is not quite what happens.
>>> print (range(10))It actually generates a range object that can say how a sequence of numbers is generated, but doesn't generate them until execution. You can then use the list() function to convert a range object into an actual list of numbers, or even tuple() to convert it to a tuple.
range(0, 10)
>>> print (list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(type(range(10)))
<class 'range'>>>>
One of the old problems with ranges in Python is that they start at 0 and end just before you expect them to. This can be worked around by specifying the starting point of a range and increasing the end point by 1. So to get a range that really is from 1 to 10,
>>> print (list(range(1, 11)))Being able to specify a starting point other than 0 can be very useful.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
As far as I am aware, ranges only deal with integers, not floating point numbers, and by default they step forward by +1 each time. The distance they step can be modified.
The range() function takes 1, 2 or 3 arguments (values in the brackets).
1 argument - The stop point
2 arguments - The start point and stop point
>>> print (list(range(10, 21)))3 arguments - The start point, the stop point and the increment per step.
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> print (list(range(10, 31, 2)))
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
>>> print (list(range(10, 20, -1)))I included the mistake of getting the starting point and end point muddled up when stepping backwards as it is the type of error I would absent-mindedly do.
[]
>>> print (list(range(20, 10, -1)))
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
>>>
No comments:
Post a Comment