The range() function in Python
Naresh Maddela
Data science & ML ll Top Data Science Voice ll 1M+ impressions on LinkedIn || Top 1% on @TopMate
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)
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
Senior Analyst | Project Management | Client Service | Team Management | SME Payroll- US
5 个月Good work...