Sometimes it is helpful to be able to just tell the computer to do something a certain number of times without having to type in every item of a range. This is why Python has a special function called range. range() takes two numbers and tells Python to count from the one to the other. By default, it does this in increments of one but can be told to do it in increments of any positive integer imaginable. The basic syntax of range() is as follows:
When the increment element is used, it goes after the end number:
range(start, end, increment)
range(0, 10, 2)
You can use range() wherever you would use a list. Whether you assign the range to a variable or use it directly in a for condition, the results are the same.
a = range(1, 10) for i in a: print i
for i in range(1, 10): print i
A word should be said here about large ranges. range() works by forming the range list when it is called. The full value of that list is then passed around the program whenever the range is needed. This consumes memory and CPU cycles, especially when range() is given a large number of items to amass. Therefore, Python has another range function called xrange(). The syntax of xrange() is exactly the same as range(), but xrange() populates its range list whenever it is accessed, allowing the memory to be freed when the list is not actively used.