The Parameters And Usage Of Ranges In Python

1. what is a range

ARG COUNT | ARG MEANING       | COMMENT
----------|-------------------|-------------------------------------
1 | stop | counting from zero
2 | start, stop | using the half-open interval (!)
3 | start, stop, step | an increment
>>> list(range(0,18,3))
[0, 3, 6, 9, 12, 15]

2. why half-open range convention and the three times -1 range arguments to parse a list backward

>>> list(range(1,4))
[1, 2, 3]
>>> list(range(4,8))
[4, 5, 6, 7]
>>> l = list(range(6))
>>> l
[0, 1, 2, 3, 4, 5]

# WRONG
>>> for i in range(len(l)-1,0,-1):print(i)
5
4
3
2
1

# CORRECT
>>> for i in range(len(l)-1,-1,-1):print(i)
5
4
3
2
1
0

3. typical usage: loop counters

>>> for i in range(7): print(i)
...
0
1
2
3
4
5
6
for _ in range(3):
print("Go Nuts")

>>> Go Nuts!
>>> Go Nuts!
>>> Go Nuts!

4. usage: list/tuple constructor

>>> list(range(5))
[0, 1, 2, 3, 4]
>>> tuple(range(5))
(0, 1, 2, 3, 4)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store