Python’s range() Function

In Python, the range() function is a versatile tool for generating numerical sequences efficiently. Let’s explore its functionality, applications, and usage through practical examples.

Understanding range() Function

The range() function in Python is used to generate a sequence of numbers. Its syntax is as follows:

range(start, stop, step)
• start: Optional parameter specifying the starting value of the sequence (default is 0).
• stop: Parameter indicating the ending value of the sequence (exclusive).
• step: Optional parameter representing the step size (default is 1).

Example 1: Generating a Sequence

for i in range(5):
print(i, end=' ')

Output 1:

0 1 2 3 4

Example 2: Specifying Start and Stop

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

Output 2:

2 3 4 5 6 7 8 9

Example 3: Using Step Size

for i in range(1, 10, 2):
print(i, end=' ')

Output 3:

1 3 5 7 9

Example 4: Creating a List

numbers = list(range(5))
print(numbers)

Output 4:

[0, 1, 2, 3, 4]

Points to Remember

• The range() function generates numerical sequences efficiently.
• It is commonly used in for loops to iterate over a sequence of numbers.
• range() supports specifying start, stop, and step parameters to customize the sequence.
• Use list(range()) to generate a list based on the range.
Author: user