1.9: Range - nealtran1905/PythonForResearch GitHub Wiki

### Ranges are immutable sequences of integers,

and they are commonly used in for loops. To create a range object, we type "range" and then we put in the stopping value of the range. Now, we've just created a range object, but this is less helpful if you would like to see what's the actual content of that object. Although, we wouldn't typically do this in a Python program, for us to really see the content of that range object, so what we can do in this case is we can turn it into a list. So if we say "list of range 5," we'll see that the range object consists of five numbers, from 0 to 4.

The input argument to range is the stopping value.

And remember, Python stops before it hits the stopping value.

That's why range 5 does actually not contain the number 5.

We can provide additional arguments to the range function. For example, we can provide the starting point, and we can also define the step size.

So if we type "range 1 to 6," in that case,

we get a range object which starts at 1 and ends at 5.

If we wanted to go in increments of two, we could do something like this. We could start from 1, go up to 13-- number 13, not itself included-- and we could go in steps of two. In this case, we get a range object that starts at 1 and ends at 11. Typically when we use range objects in our Python programs, we do not first turn them into lists. We've done it here only so that it's easier for us to understand what these objects do. You can certainly use a list object in a for loop context, but it's problematic for the following reason. To store a range object, Python is only storing three different numbers, which are the starting number, the stopping number, and its step size.

If you have a very large dataset that contains, say, 10 million objects,

if you first create a list that contains the indices for accessing

these 10 million numbers, you've just wasted a lot of space just

to be able to loop through your data.

Consequently, use range objects as is.

Don't turn them into lists before using them.