You set a range in Python using the built-in range()
function. This function generates a sequence of numbers, which can be very useful for loops and other iterative tasks. The range()
function is quite flexible, allowing you to customize the starting point, ending point, and step size of your number sequence.
Understanding the range()
Function
The range()
function has three parameters: start
, stop
, and step
.
Parameter | Description | Default Value |
---|---|---|
start |
The beginning number of the sequence. | 0 |
stop |
The number where the sequence ends (exclusive). | Required |
step |
The increment between numbers in the sequence. | 1 |
-
range(stop)
: When you provide a single argument,stop
, the sequence starts at 0, increments by 1, and stops before reaching thestop
value.for i in range(5): # Generates 0, 1, 2, 3, 4 print(i)
-
range(start, stop)
: When you provide two arguments,start
andstop
, the sequence starts atstart
, increments by 1, and stops before reaching thestop
value.for i in range(2, 7): # Generates 2, 3, 4, 5, 6 print(i)
-
range(start, stop, step)
: When you provide three arguments,start
,stop
, andstep
, the sequence starts atstart
, increments bystep
, and stops before reaching thestop
value.for i in range(1, 10, 2): # Generates 1, 3, 5, 7, 9 print(i)
Practical Applications and Insights
- The
stop
value is always exclusive, meaning the generated sequence does not include it. - The
step
value can be negative, allowing for sequences that count down. For example,range(5, 0, -1)
will generate 5, 4, 3, 2, 1. - The
range()
function does not generate a list; instead, it generates a sequence of numbers on demand, saving memory, especially for very large ranges. To create a list, uselist(range(start, stop, step))
. - The
range()
function is extremely helpful in conjunction withfor
loops for iterating a specific number of times or over a sequence of numbers.
Examples:
- Generate a list of even numbers between 10 and 20:
even_numbers = list(range(10, 21, 2)) print(even_numbers) # Output: [10, 12, 14, 16, 18, 20]
- Generate a countdown sequence from 5 to 1:
for i in range(5, 0, -1): print(i) #Output: 5, 4, 3, 2, 1
- Generate a range of numbers from -3 to 3:
numbers = list(range(-3,4)) print(numbers) # Output: [-3, -2, -1, 0, 1, 2, 3]