
Python range and arguments (start, stop, and step)
You can get consecutive integers by the range()
, a Python built-in function.
r = range(4)
for n in r:
print(n)
# 0
# 1
# 2
# 3
It returns the range object similar to list.
r = range(4)
print(r) # range(0, 4)
print(type(r)) # <class 'range'>
range()
The range()
can take arguments in two patterns.
- stop
- start, stop, (step)
The first pattern has only the stop argument. The second pattern has the start, stop, and step arguments and the step is optional.
a = range(4)
b = range(3, 10)
c = range(3, 10, 2)
a2 = list(a)
b2 = list(b)
c2 = list(c)
print(a2) # [0, 1, 2, 3]
print(b2) # [3, 4, 5, 6, 7, 8, 9]
print(c2) # [3, 5, 7, 9]
Negative step
a = range(0, -4, -1)
b = range(3, -10, -1)
c = range(3, -10, -2)
a2 = list(a)
b2 = list(b)
c2 = list(c)
print(a2) # [0, -1, -2, -3]
print(b2) # [3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
print(c2) # [3, 1, -1, -3, -5, -7, -9]
Negative step means the negative direction.
Reverse the range
a = range(5)[::-1]
b = range(7, 10)[::-1]
c = range(7, 25, 4)[::-1]
a2 = list(a)
b2 = list(b)
c2 = list(c)
print(a2) # [4, 3, 2, 1, 0]
print(b2) # [9, 8, 7]
print(c2) # [23, 19, 15, 11, 7]
You can reverse the range using Python slicing [::-1]
. This syntax is used to reverse a list, tuple, string, etc.
Comments
Powered by Markdown