Using range objects is an efficient way to represent a series of numbers, ordered by value. They are largely used for specifying the number of times a loop should run. Chapter 5 introduces loops. Range objects can take start (optional), end, and step (optional) arguments. Much as with slicing, the start is included in the range, and the end is not. Also as with slicing, you can use negative steps to count down. Ranges calculate numbers as you request them, and so they don’t need to store more memory for large ranges. Listing 3.4 demonstrates how to create ranges with and without the optional arguments. This listing makes lists from the ranges so that you can see the full contents that the range would supply.
Listing 3.4 Creating Ranges
range(10) range(0, 10) list(range(1, 10)) [1, 2, 3, 4, 5, 6, 7, 8, 9] list(range(0,10,2)) [0, 2, 4, 6, 8] list(range(10, 0, -2)) [10, 8, 6, 4, 2]