The range() function in Python

The range() function in Python


n Python, the range() function generates a sequence of numbers, which is commonly used in loops. It has three parameters: start, stop, and step. Here's a detailed breakdown of how to use it, along with examples.


Syntax

python

range(start, stop, step)        

  • start (optional): The starting value of the sequence (inclusive). Defaults to 0 if not provided.
  • stop: The ending value of the sequence (exclusive).
  • step (optional): The increment or decrement between values. Defaults to 1.


Basic Usage Examples

1. Using range(stop)

When only the stop parameter is provided, it generates numbers starting from 0 to stop - 1.

python

for i in range(5):
    print(i)        

Output:

0
1
2
3
4        

Here, range(5) generates numbers from 0 to 4.


2. Using range(start, stop)

When both start and stop are provided, it generates numbers starting from start to stop - 1.

python

for i in range(2, 7):
    print(i)        


Output:

2
3
4
5
6        

Here, range(2, 7) starts at 2 and stops before 7.


3. Using range(start, stop, step)

In this case, the step parameter controls the interval between numbers. It can also be negative to generate a reverse sequence.

python

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


Output:

1
3
5
7
9        

Here, range(1, 10, 2) starts from 1 and increments by 2.

4. Using Negative Step

If you want to count downwards, use a negative step.

python

for i in range(10, 0, -2):
    print(i)        


Output:

10
8
6
4
2        

Here, range(10, 0, -2) starts at 10 and decrements by 2 each time.

Converting Range to List

If you want to see the values generated by range(), you can convert it to a list.

python

print(list(range(5)))        

Output:

[0, 1, 2, 3, 4]        


Common Use Cases

1. Looping Through a List with Index

python

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(i, fruits[i])
        

Output:

0 apple
1 banana
2 cherry        


2. Using range() in Reverse to Loop Backwards

python

for i in range(len(fruits)-1, -1, -1):
    print(i, fruits[i])        

Output:

2 cherry
1 banana
0 apple        

  • The range() function is a powerful tool for generating sequences of numbers. With its ability to customize the start, stop, and step, it can handle a variety of situations, from counting up to counting down.


Deepak Singh

Senior Analyst | Project Management | Client Service | Team Management | SME Payroll- US

5 个月

Good work...

要查看或添加评论,请登录

Naresh Maddela的更多文章

社区洞察

其他会员也浏览了