# Python range

## Introduction

The `range` function is a built-in function in Python that generates a sequence of numbers. This sequence can be used in many different ways, including looping through a set of values, creating lists, and more. In this tutorial, we will explore the `range` function and its various applications.

## Basic Usage

The `range` function is used to generate a sequence of numbers. It takes in three arguments: `start`, `stop`, and `step`. `start` specifies the starting point of the sequence, `stop` specifies the end point of the sequence, and `step` specifies the step size between each number in the sequence.

Here’s a basic example of how to use the `range` function:

``````# generate sequence of numbers from 0 to 4
for i in range(5):
print(i)
``````

In this example, we use the `range` function with only one argument, which specifies the stop value. This generates a sequence of numbers from 0 to 4, which is then looped through using a `for` loop. The `print` function is used to display each number in the sequence.

## Using Start and Stop Values

The `range` function can also take in a `start` value in addition to the `stop` value. This allows you to generate a sequence of numbers starting from a specific value.

``````# generate sequence of numbers from 1 to 5
for i in range(1, 6):
print(i)
``````

In this example, we use the `range` function with two arguments, which specify the start and stop values. This generates a sequence of numbers from 1 to 5, which is then looped through using a `for` loop.

## Using Step Values

The `range` function can also take in a `step` value, which specifies the step size between each number in the sequence.

``````# generate sequence of even numbers from 0 to 8
for i in range(0, 10, 2):
print(i)
``````

In this example, we use the `range` function with three arguments, which specify the start value, stop value, and step value. This generates a sequence of even numbers from 0 to 8 (inclusive), which is then looped through using a `for` loop.

## Creating Lists

The `range` function can also be used to create lists of numbers. You can do this by passing the `range` function to the `list` function.

``````# create list of odd numbers from 1 to 9
odd_numbers = list(range(1, 10, 2))
print(odd_numbers)
``````

In this example, we use the `range` function to generate a sequence of odd numbers from 1 to 9. We then pass this sequence to the `list` function, which converts it into a list. Finally, we use the `print` function to display the resulting list.

`Follow us on social media`
`Follow Author`