Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Python's range() Function: From Basics to Advanced Use Cases

What is Python range?

Python's range() is a built‑in generator that produces a sequence of integers based on a start, stop, and optional step. If the start value is omitted, it defaults to 0, and the sequence increments by 1 until it reaches the stop value (exclusive). For example, range(5) yields 0, 1, 2, 3, 4. The function is indispensable when iterating with for loops.

In this tutorial you will learn:

Syntax

range(start, stop, step)

Parameters

Return Value

Returns a range object, which behaves like an immutable sequence of integers. When converted to a list, it displays the full sequence.

Python range() Function and History

Introduced in Python 3, range() replaced the older xrange() used in Python 2. The key differences are summarized below:

range()xrange()
Returns an immutable sequence of numbers.Returns a generator object.
Consumes memory proportional to the sequence length.Uses minimal memory; generates values lazily.
Suitable for small to medium-sized ranges.Preferred for large ranges or infinite sequences.
Slower on very large ranges due to memory allocation.Faster when iterating over large ranges.

Using range()

Below is a basic example that prints numbers from 0 to 9:

for i in range(10):
    print(i, end =" ")

Output:

0 1 2 3 4 5 6 7 8 9

Using start and stop in range()

Specifying a start value shifts the sequence:

for i in range(3, 10):
    print(i, end =" ")

Output:

3 4 5 6 7 8 9

Using start, stop, and step

By adding a step, you can control the interval between numbers:

for i in range(3, 10, 2):
    print(i, end =" ")

Output:

3 5 7 9

Incrementing the values with a positive step

The default step is 1, but you can specify any positive integer:

for i in range(1, 30, 5):
    print(i, end =" ")

Output:

1 6 11 16 21 26

Reverse Range: Decrementing with a negative step

Providing a negative step creates a descending sequence:

for i in range(15, 5, -1):
    print(i, end =" ")

Output:

15 14 13 12 11 10 9 8 7 6

Using floating numbers in Python range()

The built‑in range() only accepts integers. Attempting to pass a float raises a TypeError:

for i in range(10.5):
    print(i, end =" ")

Output:

Traceback (most recent call last):
  File "python_range.py", line 1, in <module>
    for i in range(10.5):
TypeError: 'float' object cannot be interpreted as an integer

Using for‑loop with Python range()

Range is often paired with len() to iterate over list indices:

arr_list = ['Mysql', 'Mongodb', 'PostgreSQL', 'Firebase']

for i in range(len(arr_list)):
    print(arr_list[i], end =" ")

Output:

Mysql Mongodb PostgreSQL Firebase

Using Python range() as a list

Converting a range to a list is straightforward:

print(list(range(10)))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using characters in python range()

While range() works only with integers, you can generate alphabet sequences by converting characters to their Unicode code points:

def get_alphabets(startletter, stopletter, step):
    for c in range(ord(startletter.lower()), ord(stopletter.lower()), step):
        yield chr(c)

print(list(get_alphabets("a", "h", 1)))

Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g']

How to Access Range Elements

You can retrieve values via iteration, indexing, or conversion to a list:

Iteration

for i in range(6):
    print(i)

Output:

0
1
2
3
4
5

Indexing

startvalue = range(5)[0]
print("The first element in range is = ", startvalue)

secondvalue = range(5)[1]
print("The second element in range is = ", secondvalue)

lastvalue = range(5)[-1]
print("The last element in range is = ", lastvalue)

Output:

The first element in range is =  0
The second element in range is =  1
The last element in range is =  4

Using list()

print(list(range(10)))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example: Get even numbers using range()

To generate even numbers up to 18:

for i in range(2, 20, 2):
    print(i, end =" ")

Output:

2 4 6 8 10 12 14 16 18

Merging two-range() outputs

Combining two range objects can be done with itertools.chain:

from itertools import chain

print("Merging two range into one")
frange = chain(range(10), range(10, 20, 1))
for i in frange:
    print(i, end =" ")

Output:

Merging two range into one
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Using range() With NumPy

NumPy’s arange() mirrors range() but supports floating‑point steps:

Syntax

arange(start, stop, step)

Example

import numpy as np

for i in np.arange(10):
    print(i, end =" ")

Output:

0 1 2 3 4 5 6 7 8 9

Floating‑point range with NumPy

for i in np.arange(0.5, 1.5, 0.2):
    print(i, end =" ")

Output:

0.5 0.7 0.8999999999999999 1.0999999999999999 1.2999999999999998

Because floating‑point arithmetic is binary, the output sometimes shows long decimal expansions. You can round the values as needed.

Summary

Python

  1. Mastering Python For Loops: Syntax, Examples, and Advanced Patterns
  2. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  3. Python Loop Control: break, continue, and pass Statements Explained with Practical Examples
  4. Master Python Lambda Functions: Practical Examples & Best Practices
  5. Python abs() Function: Compute Absolute Values for Numbers & Complex Numbers
  6. Python round() Function Explained with Practical Examples
  7. Mastering Python's range() Function: From Basics to Advanced Use Cases
  8. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  9. Mastering Python’s enumerate(): Loop with Indices for Lists, Tuples, Strings, and Dictionaries
  10. Python list.count(): Expert Guide with Practical Examples