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:
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
Output 1:
Example 2: Specifying Start and Stop
Output 2:
Example 3: Using Step Size
Output 3:
Example 4: Creating a List
Output 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.