Indexing lets you get an item at a particular position. In Python, put an integer in square brackets after a string or list. Counting starts at 0, so index 0 selects the first item. section 7.2 section 25.2
Pick one character or item
In "Python rules!", "Python rules!"[0] gives 'P' and "Python rules!"[7] gives 'r'. A space counts as a character. With grocery = ["milk", "eggs", "bread"], grocery[1] gives "eggs". section 7.2 section 25.2
Keep three position rules in mind:
- Negative indices count backward: -1 selects the last character of a string. You can also use a negative index when changing a list item. section 7.2 section 25.6
- A slice such as name[0:space] takes characters from index 0 through the position just before space. Unlike a single index, a slice gets a substring. section 12.2
- Stay within the list: a three-item list has indices 0, 1, and 2. Trying grocery[3] raises IndexError. section 25.2
An index can also help you change a list. For example, colors[0] = "orange" replaces the first item. This changes the existing list. section 25.6
Listing 12.2. Storing the first and last names in variables
space = name1.find(" ") #1
name1_first = name1[0:space] #2
name1_last = name1[space+1:len(name1)] #3
space = name2.find(" ") #4
name2_first = name2[0:space] #4
name2_last = name2[space+1:len(name2)] #4
In this name-splitting example, find(" ") locates the space. Slices on either side of that index save the first and last names separately. section 12.2
Quick check: for "Python rules!", what does index -1 select? Then try predicting which grocery item grocery[2] selects before running the code. section 7.2 section 25.2














