range() Function in Python

Python range() Function

In Python, the range() function is used to generate a sequence of numbers, which is commonly used for iterating over a loop a specific number of times. It returns an immutable sequence of numbers from a start value (inclusive) to an end value (exclusive) with a specified step size. The general syntax of the range() function is as follows:

range(start, stop, step)

Parameters:

  • start: The starting value of the sequence (optional). If not provided, it defaults to 0.
  • stop: The end value of the sequence. The range will stop before reaching this value.
  • step: The step size to increment the numbers in the sequence (optional). If not provided, it defaults to 1.

The range() function returns a range object in Python 3, which is an efficient way to represent a large sequence of numbers without actually generating them all in memory. In Python 2, it returns a list.

Here are a few examples of how to use the range() function:

Generating a sequence of numbers from 0 to 9:

for num in range(10):
    print(num)

Generating a sequence of numbers from 5 to 14 (exclusive) with a step of 2:

for num in range(5, 15, 2):
    print(num)

Using range() in a loop for iterating:

for i in range(1, 6):
    print("Iteration", i)

Creating a list of numbers using range():

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

Please note that in Python 2, the range() function returns a list instead of a range object. If you want to achieve the same memory-efficient behavior as in Python 3, you can use the xrange() function in Python 2, which provides the same functionality as range() in Python 3. However, since Python 2 is no longer supported as of January 1, 2020, it is recommended to use Python 3 for all new projects.