What is the Python range() Function and How Does It Work?

The range() function in Python is a built-in function that generates a sequence of numbers. It’s commonly used in for loops to iterate over a sequence of numbers.

Understanding range()

The basic syntax of range() is:

range(start, stop, step)

Where:

  • start (optional): The starting number of the sequence.
  • stop (required): The end of the sequence (not included).
  • step (optional): The difference between each number in the sequence.

Using range() in a for Loop

Here’s an example of how to use range() in a for loop:

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

Specifying Start and Step

You can specify the start and step parameters:

for i in range(2, 10, 2):
    print(i)
# Output: 2 4 6 8

Using range() with Negative Steps

To generate a sequence in reverse order:

for i in range(5, 0, -1):
    print(i)
# Output: 5 4 3 2 1

Converting range() to a List

You can convert a range() object to a list:

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

Memory Efficiency

The range() function is memory efficient because it generates numbers on demand (lazy evaluation) and doesn’t store the entire sequence in memory.

Conclusion

The range() function is a versatile tool in Python for generating sequences of numbers. Understanding how to use it effectively can enhance your coding efficiency.

Leave a Reply

Your email address will not be published. Required fields are marked *