Understanding the Range Function in Python: Examples and Explanation
10 Examples of Using the Range Function in Python
Generating a Sequence of Numbers from 0 to 9
# Print the numbers 0 to 9 for i in range(10): print(i)Output:
0 1 2 3 4 5 6 7 8 9
Generating a Sequence from 3 to 9
for i in range(3, 10): print(i)Output:
3 4 5 6 7 8 9
Generating a Sequence with a Step Size of 2
for i in range(0, 10, 2): print(i)Output:
0 2 4 6 8
Generating a Sequence from -10 to -1
for i in range(-10, 0): print(i)Output:
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Generating a Sequence with a Step Size of 3
for i in range(-10, 0, 3): print(i)Output:
-10 -7 -4 -1
Generating a Sequence from -5 to 5
sequence = list(range(-5, 5)) print(sequence)Output:
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
Create a List Using Range Function
numbers = list(range(10)) print(numbers)Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a List with a Step Size of 2
numbers = list(range(0, 20, 2)) print(numbers)Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]