PYTHON

Python range() Function [Python Tutorial]

The Python range() function generates a sequence of numbers in a range. By default, range() starts at 0, increments by 1, and stops before a specified number.

How to Use range() in Python

range() is a built-in function with three integer-value parameters (start, stop, and step). start is where the sequence begins, stop sets before which number it ends, and step defines the increment.

The range() function returns a sequence of integers.

Here’s the basic syntax:

range(start, stop, step)
  • start: The start value of the sequence, including the specified number.
  • stop: The optional stop value of the sequence, excluding the specified number.
  • step: The optional step value by which the range of numbers increments (1 by default).

When you call range() with a single argument, the sequence of numbers starts at 0, increments by 1, and stops before the integer number. With two arguments, the first is the start argument, and the second is the stop argument.

Basic Usage

for i in range(10):
    print(i)
# Outputs: 0 1 2 3 4 5 6 7 8 9

for i in range(1, 10):
    print(i)
# Outputs: 1 2 3 4 5 6 7 8 9

for i in range(1, 10, 2):
    print(i)
# Outputs: 1 3 5 7 9

When to Use the Python range() Function

The range() function is versatile for many Python programming tasks.

Python For Loop Ranges

Within for loops in Python, range() can control the number of iterations of the loop. This is useful when you need to repeat an action a specific number of times.

for i in range(5):
    print(i)
# Outputs: 0 1 2 3 4

Populating Lists

With the range() function, you can generate sequences for various purposes. Note, however, that range() returns a list-like (but immutable) range object. To turn the range object into an actual list, you need to use the list() function.

indices = list(range(5))
print(indices)
# Outputs: [0, 1, 2, 3, 4]

Counting Down

You can also call range() to generate ranges in reverse by providing a negative step argument. This can be particularly useful for iterating over a sequence in the opposite order.

for i in range(10, 0, -1):
    print(i)
# Outputs: 10 9 8 7 6 5 4 3 2 1

Examples of the range() Function in Python

Machine Learning Applications

A machine learning application platform might use the range() function to process large training datasets in chunks of 100. By batch-processing data, the application could minimize memory usage and improve performance.

# Processing data in chunks of 100
for i in range(0, len(data), 100):
    process_chunk(data[i:i+100])

Weather Data Applications

Weather data applications might collect temperature readings every hour and store them in a list. To analyze data only at specific intervals (e.g., every 3 hours), they could use range() with a step value.

temperatures = [22, 23, 21, 19, 20, 18, 17, 16, 15, 14, 13, 12]

# Analyzing temperatures every 3 hours
for i in range(0, len(temperatures), 3):
    print(f"Temperature at hour {i}: {temperatures[i]}°C")
# Outputs:
# Temperature at hour 0: 22°C
# Temperature at hour 3: 19°C
# Temperature at hour 6: 17°C
# Temperature at hour 9: 14°C

Web Scraping Tools

A web scraping tool might use range() to iterate over pages of results. Using a range-based for loop, it could update the URL and collect data from each page.

for page in range(1, 11):
    scrape_page(f"<https://example.com/page={page}>")

Learn More About the Python range Function

Python Range + Range

The return value of the range() function is an immutable sequence of integers. To add together two ranges, you need to convert the sequences into lists beforehand.

range1 = range(5)
range2 = range(5, 10)

# Convert to lists and concatenate
combined_list = list(range1) + list(range2)
print(combined_list)
# Outputs: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python Reverse-Order Range

To reverse a range, you can also use the reversed() function with range(). Reversing the order of a range can help you iterate over a sequence in the opposite order, like in countdowns.

reversed_range = list(reversed(range(1, 11)))
print(reversed_range)
# Outputs: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Skipping Elements in a Range

You can skip elements in a range by specifying a step value greater than 1. This allows you to create sequences with intervals other than the default increment of 1. With a step of 2, for example, you can generate a sequence of even numbers.

skipped_range = list(range(0, 12, 2))
print(skipped_range)
# Outputs: [0, 2, 4, 6, 8, 10]

Floating-Point Ranges

By default, range() only supports integer values as arguments. However, you can create sequences with other data types, such as floats or tuples, by defining a custom function.

def float_range(start, stop, step):
    while start < stop:
        yield float(start)
        start += step

for num in float_range(0.5, 2.0, 0.5):
    print(num)
# Outputs: 0.5 1.0 1.5

Python List Index Out of Range

Using the range() function to generate list indices can lead to IndexError-type errors. To prevent such errors, you can create for loops with the list to iterate over instead of a range of indices. If you prefer, you can also catch errors using a try...except statement.

example_list = [1, 2, 3]
for item in example_list:
	print(item)
	
try:
    for i in range(3):
        print(example_list[i])
except IndexError:
    print(f"Index {i} is out of range")
# Outputs: Index 3 is out of range

Performance Considerations in For Loops

Using range() to iterate over indices rather than elements avoids creating additional lists and optimizes memory. Particularly in large lists of large objects, accessing items by index can be much more efficient with range().

data = ["apple", "banana", "cherry"]
for i in range(len(data)):
    print(f"Index {i}: {data[i]}")

Python range vs. xrange

Python 2 has a built-in function called xrange() to create ranges. With Python 3, range() took over and extended the functionality of xrange(). If you want to keep your Python code compatible between the two programming language versions, range() is the better choice.

# Legacy Python 2.x
for i in xrange(10):
    print(i)
# In Python 3.x, use `range` directly
Learn Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH