The range
function lets us build a list of numbers.
list(range(10, 20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Notice anything funny?
Python uses this convention everywhere.
a = list(range(10, 20))
type(a)
list
Let's talk about indexing.
Indexing in Python starts at 0.
a[0]
10
And goes from there.
a[1]
11
a[2]
12
What do negative numbers do?
a[-1]
19
a[-2]
18
You can get a sub-list by slicing.
a[3:7]
[13, 14, 15, 16]
Start and end are optional.
a[3:]
[13, 14, 15, 16, 17, 18, 19]
a[:3]
[10, 11, 12]
Again, notice how the end entry is not included:
print(a[:3])
print(a[3])
[10, 11, 12] 13
Slicing works on any collection type! (list
, tuple
, str
, numpy
array)
a = "CS357"
a[-3:]
'357'