Python range() Function

Streamline iteration and numerical tasks with the Python range() function. This built-in function simplifies creating sequences of numbers, eliminating the need for manual loops or list creation. Use range() to generate numbers on the fly, optimize your code for efficiency, and enhance readability in your Python programs

Python-range()-Function
Table of Contents

What is the range() Function in Python?

Python range() function is a handy tool for generating sequences of numbers. It creates an iterable (sequence-like object) containing numbers within a specified range.

Python range() Function Syntax

number_sequence = range(start, stop, step)

  • start (optional): This defines the first number in the sequence (defaults to 0).
  • stop: This is the number before the sequence stops (not included).
  • step (optional): This argument defines the difference between each number in the sequence (defaults to 1).

Python range() Function Example

# Generate numbers from 0 to 4 (stop value is not included)
numbers = range(5)

# Print the sequence of numbers
print(numbers)  # Output: range(0, 5)

# Generate numbers from 2 to 10 with a step of 2 (even numbers from 2 to 8)
even_numbers = range(2, 10, 2)

# Print the sequence of even numbers
print(list(even_numbers))  # Output: [2, 4, 6, 8] 

Explanation

  • Line 2: Creates a sequence of numbers from 0 to 4 (excluding 4) using range(5).
  • Line 5: Prints the generated sequence object, which isn’t directly printable but shows the start and stop range.
  • Line 8: Creates a sequence of even numbers from 2 to 9 (excluding 10) with a step of 2 using range(2, 10, 2).
  • Line 11: Converts the sequence to a list using list() for printing. This is because range() itself returns an iterable object, not a list.

Output

range(0, 5)
[2, 4, 6, 8]


Why Use the range() Function?

The range() function in Python is a powerful tool for generating sequences of numbers. This versatile function has several key uses in your Python code:

Controlling Loops

When you need to execute a block of code a specific number of times, the range() function provides an easy way to iterate over a numerical sequence. This is more efficient than manually creating a list of numbers for the same purpose.

Generating Number Lists

Although range() itself returns an iterable object; you can easily convert it into a list using the list() function. This allows you to create lists of numbers with specific patterns (e.g., even numbers, numbers in multiples of 10).

Accessing List Elements by Index

Since lists and other sequences in Python use zero-based indexing, range() is perfect for generating the indices needed to access items within a sequence. For example, to print each item in a list, you might use a loop like for index in range(len(my_list)).

Optimization

The range() function is more memory efficient than directly creating and storing a full list of numbers, especially when dealing with large sequences. This optimization is because range() generates the values as needed, rather than all at once.


Python range(stop)

The simplest form of range() requires only one argument, the stop value. This defines the upper limit (not included) for the generated sequence.

Syntax

number_sequence = range(stop)

Example

# Generate a sequence of numbers from 0 to 4 (stop value is not included)
numbers = range(5)

# Print the sequence of numbers
print(numbers)  # Output: range(0, 5)

Explanation

  • Line 2: Creates a sequence of numbers from 0 to 4 (excluding 4) using range(5). Here, stop is set to 5, but the sequence stops before 5.
  • Line 5: Prints the generated sequence object, which isn’t directly printable but shows the start and stop range.

Python range(start, stop)

In Python, the range() function offers more control over the generated sequence using two arguments: start and stop.

Syntax

number_sequence = range(start, stop)

Example

# Generate numbers from 3 to 8 (stop value is not included)
numbers = range(3, 8)

# Print the sequence of numbers
print(numbers)  # Output: range(3, 8)

Explanation

  • Line 2: Creates a sequence of numbers from 3 to 7 (excluding 8) using range(3, 8). Here, start is set to 3 (included) and stop is set to 8 (not included).
  • Line 5: Prints the generated sequence object, which shows the start and stop range.

Python range(start, stop, step)

You can use all three arguments—start, stop, and step—to comprehensively control the sequence of numbers generated by range() in Python.

Syntax

number_sequence = range(start, stop, step)

Example

# Generate even numbers from 2 to 10 (stop value is not included)
even_numbers = range(2, 11, 2)

# Print the sequence of even numbers
print(even_numbers)  # Output: range(2, 10, 2)

# Print the list of even numbers (converted from the sequence)
print(list(even_numbers))  # Output: [2, 4, 6, 8]

Explanation

  • Line 2: Creates a sequence of even numbers from 2 to 10 (excluding 10) with a step of 2 using range(2, 11, 2). Here, start is 2 (included), stop is 11 (not included), and step is 2 (adding 2 to get the next number in the sequence).
  • Line 5: Prints the generated sequence object, which shows the start, stop, and step values.
  • Line 6: Converts the sequence to a list using list() for printing. This is because range() itself returns an iterable object, not a list directly.

Positive Step And Negative Step Values

Python Range function allows you to control how the sequence progresses using a step value. A positive step creates an incrementing sequence, while a negative step generates a decrementing sequence.

Example

# Positive step: Incrementing by 2 (start at 0, stop before 10)
for num in range(0, 10, 2):
    print(num, end=" ")

# Negative step: Decrementing by 3 (start at 10, stop before 1, exclude 1) 
for num in range(10, 0, -3):
    print(num, end=" ")

Explanation

  • Lines 2-3: Loop through a range(0, 10, 2) sequence, which starts at 0, stops before 10, and increments by 2. The end=" " argument in print keeps numbers on the same line.
  • Lines 6-7: Loop through a range(10, 0, -3) sequence, which starts at 10, stops before 1 (excluding 1), and decrements by 3.

Output

0 2 4 6 8 10 7 4 1


Generating Reversed Sequences with reversed()

While the range() function excels at generating sequences in a forward order, Python doesn’t have a built-in way to directly create a reversed range. However, you can combine range() with the reversed() function to achieve this.

Example

# Generate a sequence from 5 to 1 (reversed order)
numbers = range(1, 6)  # Regular range from 1 to 5 (stop value not included)

# Reverse the sequence using reversed()
reversed_numbers = reversed(numbers)

# Print the numbers in reverse order (using a loop)
for num in reversed_numbers:
    print(num)

Explanation

  • Line 2: Creates a regular range(1, 6) sequence, starting at 1 and stopping before 6.
  • Line 5: Applies the reversed() function to the numbers sequence, creating an iterator that will iterate through elements in reverse order.
  • Lines 8-9: Loop through the reversed_numbers iterator, printing each number in the reversed order (from 5 to 1).

Output

5
4
3
2
1


Concatenating range() Outputs

While Python’s range() function directly generates sequences of numbers, you can’t concatenate two range objects themselves. However, there are a couple of ways to achieve a combined sequence. Here’s a common approach using a list:

Example

# Create two range sequences
first_sequence = range(1, 4)  # Numbers from 1 to 3 (excluding 4)
second_sequence = range(5, 8)  # Numbers from 5 to 7 (excluding 8)

# Combine the sequences using list concatenation
combined_sequence = list(first_sequence) + list(second_sequence)

# Print the elements of the combined sequence
for num in combined_sequence:
    print(num)

Explanation

  • Lines 2-3: Create two separate range sequences, first_sequence and second_sequence.
  • Line 6: Converts both range objects to lists using list(). Then, combine them using the list + operator to create a new list combined_sequence containing elements from both ranges.
  • Lines 9-10: Loop through the combined_sequence list and print each number.

Output

1
2
3
5
6
7


Accessing range() with an Index Value

While range() in Python is excellent for generating sequences for loops, you cannot directly access elements within the sequence using indexing like a list. However, you can combine range() with a loop to achieve this. 

Example

# Generate a sequence from 0 to 4
numbers = range(5)

# Loop through the indices and access elements using the index
for idx in range(len(numbers)):
    print(f"At index {idx}, value is {numbers[idx]}")

Explanation

  • Line 2: Creates a range(5) sequence containing numbers from 0 to 4 (excluding 4).
  • Lines 5-6: Loop through a range(len(numbers)) sequence. This creates a loop that iterates the same number of times as the number of elements in numbers. Inside the loop:
    • idx represents the current index (0, 1, 2, 3, 4).
    • numbers[idx] accesses the value at the corresponding index within the numbers sequence.

Output

0 index, value is 0
1 index, value is 1
2 index, value is 2
3 index, value is 3
4 index, value is 4


Convert range() to list

In Python, the range() function is an efficient way to generate sequences of numbers. However, range() itself returns an iterable object, not a list. To use the elements in various list functions or access them by index, you can easily convert a range() object to a list.

Example

# Generate a sequence of numbers from 0 to 4 (stop value not included)
number_sequence = range(5)

# Convert the sequence to a list using list()
number_list = list(number_sequence)

# Print the elements of the list
print(number_list)  # Output: [0, 1, 2, 3, 4]

Explanation

  • Line 2: Creates a sequence of numbers from 0 to 4 (excluding 4) using range(5).
  • Line 5: Converts the number_sequence (which is a range object) to a list using the list() function. This creates a new list number_list containing the same elements as the original sequence.
  • Line 8: Prints the number_list, which now behaves like a regular Python list.

Benefits of Using range()

Here are some key benefits of using the range() function in Python:

  • Memory efficiency: Especially for large sequences, range() avoids pre-generating and storing a whole list of numbers simultaneously.
  • Optimized looping: Works seamlessly with for loops to control iterations over numeric sequences.
  • Index-based element access: Easily generate indices for accessing elements of lists or other sequences.
  • Readable and versatile: Clear syntax makes creating and manipulating sequences for various uses easy.
  • Speed and efficiency (vs. manual list creation): Eliminates the need to manually create and add items to a list, saving time and resources.

Common Pitfalls and Considerations

Here are some common pitfalls and considerations to keep in mind when using the range() function in Python:

  • Off-by-one errors: The stop value in range() is excluded, so adjust accordingly to get your desired sequence.
  • List conversion needed for some operations: range() returns an iterable object, not a list; use list(range(...)) for list-specific operations.
  • Large ranges and memory: For extremely large ranges, xrange() (Python 2) or iterator-based approaches may be even more memory efficient.
  • Negative step reverses order: Using a negative step value will make range() generate numbers in reverse.
  • Potential index errors: Be cautious when using range() to index other sequences, ensuring the lengths align to avoid out-of-bounds errors.