Today we’ll be talking about ranges.
A range is a sequence of integer numbers.
The range function is used to generate a range. We can cast the result to a list using the function list.
The range function takes 1, 2 or 3 parameters. The syntax is:
range(start_value, past_value, step)
The sequence of the generated numbers begins with start_value and ends just before past_value, so past_value is not included. The range function requires at least one parameter. It’s the past_value. If it’s the only parameter, start_value is assumed to be equal to zero:
>>> list(range(6)) # from 0 to 5
[0, 1, 2, 3, 4, 5]
If we use 2 parameters, these are the start_value and the past_value. The step is assumed to be equal to 1:
>>> list(range(4, 17)) # from 4 to 16
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
We can also use negative integers:
>>> list(range(-12, -7)) # from -12 to -8
[-12, -11, -10, -9, -8]
If we use all three parameters, the last one determines the step. So, if the step is equal to 3, every third number will be picked:
>>> list(range(-10, 10, 3))
[-10, -7, -4, -1, 2, 5, 8] # from -10 to 9, every third number
We can use a negative step to move in reversed direction:
>>> list(range(20, 0, -1)) # from 20 down to 1
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(range(20, 0, -2)) # from 20 down to 1, every other number
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
Slicing Ranges in Python
We can slice ranges. Slicing means extracting subranges or sublists. Here’s an example: Let’s generate a sequence of integers from 1 to 10:
>>> a = range(1, 11)
What we have is the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Each element of the sequence has an index. The first element has the index 0, the second element has the index 1, and so on.
Now we can slice the range using the indices. The syntax is:
a[start_index : past_index]
where a is the range.
So we get the subrange between the element at start_index and the one at the index one less than the past_index. Suppose we need a subrange of all the elements between index 2 and index 4. So we have to use 5 for the past_index, because it’s not included:
>>> b = a[2:5]
Now we have the subrange b. Its first element was at index 2 in the original range, so it’s 3. The last element taken was at index 4, so it’s 5. So we have:
>>> list(b)
[3, 4, 5]
Here’s the video version of the article: