CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Ranges – A walk through with Examples

A range is another sequence type in Python and it is a collection of numbers. We have discussed about Python’s sequence types; list and tuple sequence types through our previous Articles. In this Article, we will discuss about range sequence type.

As I mentioned above, range is nothing but a collection or sequence of numbers; yes, just NUMBERS ONLY. It doesn’t allow any other data types other than Integers.

Create a Range

We can create ranges by using the range class constructors. range class has two constructors; one is:

range(N) – it generates a sequence of ‘N’ numbers; staring from 0 to (N-1).

Another variation of the range constructor is:

range(start, stop, step) – it generates a sequence of numbers from start to stop (excluding); with the increment of step value.

Lets’ take a simple example to demonstrate the creation of ranges:

>>> range(10)
range(10)
>>> 

Above example, creates a range from 0 to 9.

Another example is; create a range starting from 1 to 20 (excluding) with the incremental value of 3:

>>> range(1, 20, 3)
range(1, 20, 3)
>>> 

This creates a range of values; 1, 4, 7, 10, 13, 16, 19.

Access range elements

You might have observed the results from above examples; showing the ranges instead of its’ elements or values. Unlike, lists or tuples; ranges doesn’t create the values until you access them. This way ranges takes less memory; compare to lists and tuples, where all the values are generated and stored in the memory.

We can access the ranges using its’ index value. The index starts from 0 to (number of range elements – 1). Ranges also allows negative indexes to access its’ elements from the end. For example, below statements display the first and last elements of a range.

>>> r = range(1, 20, 3)
>>> r[0]
1
>>> r[-1]
19

To display all the elements of a range, we can iterate through the range and display each element. Below example shows this:

>>> for x in r:
...    print(x)
... 
1
4
7
10
13
16
19
>>> 

Modify range elements

Ranges are immutable; that means, you can’t modify its’ values. If you attempt to modify its’ elements; Python interpreter will throw the TypeError; like below:

>>> r[3] = 10
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'range' object does not support item assignment
>>>

Commonly we use ranges, for looping in for loops.

We will discuss more about Python in my upcoming Articles.

/Shijit/

Python – Ranges – A walk through with Examples

2 thoughts on “Python – Ranges – A walk through with Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top