Python range() function
Python range() function

Python range() function

Using a for loop with range(), we can repeat an action a specific number of times

How to use range() function in Python

Python range() function generates the immutable sequence of numbers starting from the given start integer to the stop integer. The range() is a built-in function that returns a range object that consists series of integer numbers, which we can iterate using a for loop. Below is the syntax of the range() function.

range(start, stop , [step])

it takes three arguments. Out of the three, two are optional. The start and step are optional arguments and the stop is the mandatory argument.

Parameters

  • start: (Lower limit) It is the starting position of the sequence. The default value is 0 if not specified. For example, range(0, 10). Here, start=0 and stop = 10
  • stop: (Upper limit) generate numbers up to this number, i.e., An integer number specifying at which position to stop (upper limit). The range() never includes the stop number in its result
  • step: Specify the increment value. Each next number in the sequence is generated by adding the step value to a preceding number. The default value is 1 if not specified. It is nothing but a difference between each number in the result. For example, range(0, 6, 1). Here, step = 1.

Return Value

It returns the object of class range.

print(type(range(10)))

Steps to use range() function

The range() function generates a sequence of integer numbers as per the argument passed. The below steps show how to use the range() function in Python.

  1. Pass start and stop values to range()
  2. For example, range(0, 6). Here, start=0 and stop = 6. It will generate integers starting from the start number to stop -1. i.e., [0, 1, 2, 3, 4, 5]

  3. Pass the step value to range()
  4. The step Specify the increment. For example, range(0, 6, 2). Here, step = 2. Result is [0, 2, 4]

  5. Use for loop to access each number
  6. Use for loop to iterate and access a sequence of numbers returned by a range().

image

1. Guide range() Examples: stop, start, step

2. Convert range() to list

3. Concatenating the result of two range()

4. The range() indexing and slicing

5. Python range of float numbers