The range() function in Python allows you to generate a sequence of integers. When you create a_range object, based upon this range() function, it produces a generator. It doesn’t look like it is a sequence of integers, but when asked to produce its elements, it will. A simple way to cause that to occur, is to use the list() function to convert the list of generated integers and then you can see which elements it contains. And you can see that, in this case, the list of a_range, which essentially started at index 0, goes up to, but not including, 5 will produce five numbers; 0 through 4.
# The range function generates a sequence of integers a_range = range(5) print('a_range ->', a_range) print('list(a_range) ->', list(a_range)) # It is often used to execute a "for" loop a number of times for i in range(5): print(i, end=' ') #executed five times print() # It is similar to the slice function with a start, stop and step a_range = range(10) # stop only print('list(a_range) ->', list(a_range)) a_range = range(10, 16) # start and stop print('list(a_range) ->', list(a_range)) a_range = range(10,-1, -1) # start, stop and step print('list(a_range) ->', list(a_range)) The output : a_range -> range(0, 5) list(a_range) ->[0, 1, 2, 3, 4] 0 1 2 3 4 list (a_range) -> [0, 1, 2, 3, 4, 5, 6, 7, 8,9] list (a_range) -> [10, 11, 12, 13, 14, 15] list (a_range) -> [10, 9,8, 7, 6, 5, 4, 3, 2, 1, 0]
Likewise, if you use a start and a stop, it will actually start at the specified start index and it will go up to, but not include, the final stop value. In that case, 10 through 15 are the integers and the sequence that’s generated, because it goes up to, but not including, 16. You can use negative values for the range object as well, on any of the things for start, stop, or step. And the final example, we see that it will start at 10, it will go up to, but not including -1, and it will step by -1. So as we see, when the list of integers is produced, it starts at 10, it goes up to, but not including -1, so it stops at zero. We’ll see more about the range() function again when we discuss that for loop that was used in this example. But for now, that should provide you a basic understanding of how the range() function works in Python.
a_range =range(10, 16) # start and stop print('list(a_range) ->', list(a_range)) a_range = range(10, -1, -1) # start, stop and step print('list(a_range)->', list(a_range)) The output : list (a_range) -> [10, 11, 12, 13,14, 15] list (a_range) -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]