3.3. Accessing Sequence Data¶
As lists and strings are collections of items, it would be useful to have a method for accessing the individual elements of the sequence. In this section we introduce both methods of accessing data from Python sequences: indexing for a single element and slicing for a sub-sequence.
3.3.1. Index Operator¶
The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from position 0 to position 13.
It is also the case that the positions are named from right to left using negative numbers where -1 is the rightmost index and so on. Note that the character at index 6 (or -8) is the blank character.
In [1]: school = "Luther College"
In [2]: school[2]
Out[2]: 't'
In [3]: school[-1]