range() in Python allows us to create a sequence of numbers from a starting point up to an ending point.
Syntax:
1 2 3 4 5 | range(<ending_point>) #OR range(<starting_point>, <ending_point>) #OR range(<starting_point>, <ending_point>, <increment_step>) |
Let’s see some examples using range():
1 2 3 | #default starting point is always 0 x = range(10) print(x) |
Output
1 | range(0, 10) |
1 2 3 | #converting range to list x = list(range(10)) print(x) |
Output
1 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Note: The last element is always excluded in range().
1 2 3 | #using for loop to print range elements for element in range(10): print(element) |
Output
1 2 3 4 5 6 7 8 9 10 | 0 1 2 3 4 5 6 7 8 9 |
1 2 3 | #using range & for loop to print even numbers till 20 for element in range(2, 20, 2): print(element) |
Output
1 2 3 4 5 6 7 8 9 | 2 4 6 8 10 12 14 16 18 |
Comment your suggestion or doubts below.