Python range() Built in Function

The range() function is used to create and return a sequence of integer numbers as per the argument passed. The syntax of this function is:

range(start, stop, step)

The start parameter is optional and specifies the starting number of the sequence. The default value is 0. The stop parameter is required and specifies the end number of the sequence (exclusive). The step parameter is optional and specifies the increment or decrement of the sequence. The default value is 1.

The range() function can be used with for loops to iterate over a sequence of numbers. It can also be used with list() function to create a list of numbers. Here are some examples of using the range() function in Python:

To create a sequence of numbers from 0 to 5, and print each item in the sequence:

x = range(6)
for n in x:
    print(n)
# prints 0 1 2 3 4 5

To create a sequence of numbers from 10 to -10, with a step of -2, and print each item in the sequence:

x = range(10, -11, -2)
for n in x:
    print(n)
# prints 10 8 6 4 2 0 -2 -4 -6 -8 -10

To create a list of even numbers from 0 to 20 using range() and list() functions:

x = list(range(0,21,2))
print(x)
# prints [0,2,4,6,8,10,12,14,16,18]

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions