Python Range() Function with Examples

What is range() function in Python? The range() function in Python is used for generating sequences of numbers. With its simple syntax and flexible arguments, the range function is one of the most commonly used functions in Python. In this article, we’ll take a closer look at the range function, including its syntax, and how to use it in different scenarios.

1. Quick Examples of Python range() Function

These quick examples of the Python range function demonstrate some of the basic ways to use this powerful tool. We will explore additional ways to use range in Python.


# Generate list using range()
my_list = list(range(10))
print(my_list)

# Access specific element in range()
my_range = range(1, 10, 2)
print(my_range[2])

# Generate range with negative step value
my_list = list(range(10, 0, -1))
print(my_list)

# Generate range using itertools count()
from itertools import count
my_range = count(1, 2)
for i in range(5):
    print(next(my_range))

2. Syntax of Python range() Function

The range() function in Python has the following syntax:


# Syntax
range(start, stop[, step])

2.1 Parameters of the range() Function

The range() function has 3 paramters:

  • stop (required): The stopping value of the sequence. The sequence will end at this value, but will not include it.
  • start (optional): If this parameter is not provided, the sequence will start at 0.
  • step (optional): If this parameter is not provided, the step size will default to 1.

2.2 Return Value of range() Function

The range() returns a sequence of numbers, represented as a range object.

2.3 Examples of range() Function

In this example, we use the Python range() function to generate a sequence of numbers from 0 to 3 and print each number in the sequence using a for loop.


# Print numbers from 0 to 4 
for num in range(0, 4):
    print(num)

# Output:
# 0
# 1
# 2
# 3

The following is the second example. The range() function is used to generate a sequence of even numbers from 2 to 6 and print each number in the sequence using a for loop.


# Print even numbers from 2 to 8 
for num in range(2, 8, 2):
    print(num)

Use the range() function to generate a sequence of numbers from 1 to 5 and convert the resulting range object to a list.


# Generate a list of numbers from 1 to 5 
num_list = list(range(1, 6))
print(num_list)

# Output : 
# [1, 2, 3, 4, 5]

3. range() – Generate List

We can generate a list of numbers, by passing the range object to the list() function, which converts the range object into a list.

The Python range Object is to be created using the Python range() function. See the following example.


# Generate a list of numbers from 0 to 4 
num_list = list(range(5))
print(num_list)

# Output : 
# [0, 1, 2, 3, 4]

4. range() – Access Specific Elements of List

By using the range() function to access specific elements in a sequence, we can quickly and easily manipulate data without having to modify the original sequence.

For example, if you have a list and you want to access every other element starting from the second element, you could use a range object with a start value of 1 and a step value of 2.


# Get list values by Index
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(1, len(my_list), 2):
    print(my_list[i])

5. range() – With Negative Step Values

Using a negative step value with the range() function to iterate over a sequence in reverse order. we can also use a negative step value to generate a sequence of decreasing numbers.


# Range with negative step value
for i in range(5, 0, -1):
    print(i)
    
# Output:
# 5
# 4
# 3
# 2
# 1

key points to keep in mind when using negative step values with the range() function:

  1. Start value must be greater than the end value when using a negative step value.
  2. End value is always excluded from the range, regardless of the step value.
  3. Step value must be negative when iterating in reverse.
  4. Negative steps can be useful for reversing the order of a list or string.

6. Python Range Using Numpy arrange

The numpy.arange() method can easily generate a range of values with a specified start, stop, and step, and we can take advantage of the many benefits of the NumPy library. numpy.arange() can generate sequences with non-integer values, and it allows for more precise control over the step value.


import numpy as np

# Generate range using arange
my_range = np.arange(0, 10, 2)

# Print the range
print(my_range)

The table that highlights some differences between Python range() and NumPy arange():

range()numpy.arange()
FunctionBuilt-in Python functionNumpy array function
ArgumentsStart, stop, stepStart, stop, step, data type
Data typesOnly integersFloats, integers
Return typerange object (lazy evaluation)Numpy array
InclusiveExclusive of stop valueInclusive of stop value
StepCan only be an integerCan be a float or an integer
MemoryUses less memoryUses more memory
Use casesBest suited for integer sequencesBest suited for numerical computations

7. itertools count() – Generate Python Range

Another way to generate a range in Python is by using the count() function from the itertools module. This function generates an infinite sequence of numbers starting from a given value with a specified step size.


from itertools import count, islice

# Generate a range of 10 elements starting from 0 with a step of 2
my_range = islice(count(0, 2), 10)

# Print the elements of the range
for num in my_range:
    print(num)

8. enumearte() vs Python range()

While both the enumerate() and range() functions can be used to generate a sequence of numbers, they serve different purposes. The range() function generates a sequence of numbers, which can be used to iterate through a loop a specific number of times or to generate a list of numbers.

On the other hand, the enumerate() function generates a sequence of pairs, where each pair consists of an index and an element from a given iterable.


# Example using range()
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
    print(i, my_list[i])
    
# Output: 
# 0 apple
# 1 banana
# 2 cherry
    
# Example using enumerate()
for i, item in enumerate(my_list):
    print(i, item)

# Output: 
# 0 apple
# 1 banana
# 2 cherry

9. Python Range Examples

10. Summary and Conclusion

We covered several use cases for the range() function in Python, including generating a sequence of numbers, accessing specific elements in a sequence, and generating a list using the numpy.arange() function. I hope this article has provided you with a good understanding of the range() function and its various applications. If you have any further questions, please feel free to leave a comment below.

Happy Coding!

AlixaProDev

I am an astute software engineer with extensive 3+ years of experience in developing full-stack web applications. My skillets include building backend services for different databases. Mainly I work with Python, Flask, Django, and FastAPIs. Being Python Specialist, I have worked with Numpy, Pandas, and other Python Libraries to build tools that make ETL normalization easier.

Leave a Reply