Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python range Function

Python

Uploaded by

manu1202manu123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python range Function

Python

Uploaded by

manu1202manu123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python range() Function

Definition:
• The range() function in Python generates a sequence of integers, which is commonly used in for loops to
iterate over a block of code multiple times.
• The range() function has the following syntax:
range(start, stop[, step])
start: The starting integer of the sequence (default is 0).
stop: The ending limit, not inclusive.
step: The difference between each number in the sequence (default is 1).
Basic Usage Examples:
Example 1: Using range() with One Argument
for i in range(5):
print(i, end=', ')
Output:
0, 1, 2, 3, 4,
Explanation: Only the stop value is provided, so it defaults to starting from 0 and increments by 1.

Example 2: Using range() with Two Arguments


for i in range(5, 10):
print(i, end=', ')
Output:
5, 6, 7, 8, 9,
Explanation: The range starts at 5 and stops at 10, not including 10.

Example 3: Using range() with Three Arguments


for i in range(1, 10, 2):
print(i, end=', ')
Output:
1, 3, 5, 7, 9,
Explanation: The sequence starts at 1, ends at 10 (not inclusive), and increments by 2 (step size).

3. Key Points about range()


• range() works only with integers.
• All arguments must be integers (start, stop, and step).
• Step value must not be zero (will raise ValueError if set to zero).
• Negative step values allow for creating sequences that count backward.
Advanced Use of range():
Negative Steps
for i in range(10, 0, -2):
print(i, end=', ')
Output:
10, 8, 6, 4, 2,
Explanation: A negative step generates a descending sequence.
For negative steps, start value must be greater than stop value, otherwise range will be empty.

range() in Combination with len()


You can use range() with the length of a list to iterate over its indices.
my_list = [3, 6, 9]
for i in range(len(num)):
print(f"Index[{i}] Previous Value: {my_list[i]} Now: {my_list[i] * 2}")
Output:
Index[0] Previous Value: 3 Now: 6
Index[1] Previous Value: 6 Now: 12
Index[2] Previous Value: 9 Now: 18

Converting range() to a List


Python 3's range() returns a generator, but you can convert the result to a list:
even_list = list(range(2, 10, 2))
print(even_list)
Output:
[2, 4, 6, 8]

Reversing a Range
You can reverse a range using a negative step or the reversed() function:
My_list = list(reversed(range(5)))
print()
Output:
[4, 3, 2, 1, 0]

You might also like