Sequence Types - Range

Indices and tables

Range

MUTABILITY: Immutable

Creates an immutable sequence of integers. This class is commonly used to create a range of indexes to loop over. It can be used to fill other container types with content, if desired.

If you don’t need to interact with the sequence, using a range is cheaper then using a list or tuple as the range object only stores the start, stop and step values (calculating individual items and sub-ranges on the fly as required).

Ranges can only be created using the range constructor.

range(start=0, end=None, step=1),

Some examples:

  • Create a sequence to represent the values 0 to 9:

    >>> foo = range(10)
    >>> foo
    range(10)
    

    In this case, foo points to the range object. Feed the range object to the tuple or list constructor to see the actual values, as in:

    >>> list(foo)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  • Populate a list with values between 0 and 9, skipping every other one:

    >>> list(range(0, 10, 2))
    [0, 2, 4, 6, 8]
    
  • Populate a list with values between -1 and -9, skipping every other one:

    >>> list(range(-1, -10, -2))
    [-1, -3, -5, -7, -9]
    

Range Specific Methods

There are no range specific methods.

Try it!

Try creating the following objects:

  • A list of the integers between 0 and 15.
  • A list of the integers between 5 and 20.
  • A list of every 5th integer between 5 and 20.