liveBook · Manning

Indexing

As explained in Get Programming: Learn to code with Python

Indexing is the organization or use of positions, keys, or lookup structures to identify and retrieve selected data or elements.

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

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through zero-based and negative character positions plus out-of-range list errors, without exploring implementation internals.
Examples
Uses a grocery list and a full-name splitting program to show element access and slice boundaries.
What it assumes
Assumes basic familiarity with variables and strings while teaching zero-based positions and square-bracket selection.
What you can do after
Apply it via Python square brackets to read elements, extract name substrings, and update mutable list items.
How it connects
Connects indexing to slicing, substring search, sequence length, and list mutation.

Also explained in

Compare how 15 books explain indexing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.