Python 3home |
Introduction to Python
davidbpython.com
Subscripting allows us to select individual elements of a list.
fields = ['jw234', 'Joe', 'Wilson', 'Smithtown', 'NJ', '2015585894']
var = fields[0] # 'jw234'
var2 = fields[4] # 'NJ'
var3 = fields[-1] # '2015585894' (-1 means last index)
Slicing allows us to select multiple items from a list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
first_four = letters[0:4]
print(first_four) # ['a', 'b', 'c', 'd']
# no upper bound takes us to the end
print(letters[5:]) # ['f', 'g', 'h']
Here are the rules for slicing:
1) the first index is 0 2) the lower bound is the 1st element to be included 3) the upper bound is one higher the last element to be included 4) no upper bound means "to the end"
Slicing a string selects characters the way that slicing a list selects items.
mystr = '2014-03-13 15:33:00'
year = mystr[0:4] # '2014'
month = mystr[5:7] # '03'
day = mystr[8:10] # '13'
Again, please review the rules for slicing:
1) the first index is 0 (first character) 2) the lower bound is the 1st character to be included 3) the upper bound is one higher the last character to be included 4) no upper bound means "to the end"
An IndexError exception indicates use of an index for a list element that doesn't exist.
mylist = ['a', 'b', 'c']
print(mylist[5]) # IndexError: list index out of range
Since mylist does not contain a sixth item (i.e., at index 5), Python tells us it cannot complete this operation.