liveBook · Manning

Indexing

As explained in Python Workout, Second Edition

An index is a numeric position identifying an element within an ordered sequence.

Use square brackets with a numeric position to retrieve one element from a string, list, or tuple: s[0] returns the first element and s[-1] the final one. A single index retrieves an element, while a slice such as s[2:5] retrieves elements up to, but not including, the ending position. section 4.3

Keep these indexing distinctions in mind:

  • Single indexes must remain within the sequence bounds; slices tolerate endpoints beyond the data and stop at the available boundary. section 4.3
  • An indexed element may have any type, while a slice preserves the sequence type: list slices remain lists and tuple slices remain tuples. section 4.3
  • Use enumerate when iteration needs both each item and its numeric index; unpack its two-element results directly in the loop. section 2.15

A reusable first-and-last operation

def firstlast(sequence): return sequence[0] + sequence[-1] firstlast(('a', 'b', 'c')) # 'ac' firstlast((1, 2, 3, 4)) # 5 The same function works with different sequence types because both support numeric indexes. section 4.3

for index, one_letter in enumerate('abcd'):
    print(f'{index}: {one_letter}')

Run the enumerate example to see each character paired with its numeric position. section 2.15

How Python Workout, Second Edition covers it

How deep it goes
Explains element access, negative positions, slice boundaries, result types, bounds, and enumerate, without descending into implementation internals.
Examples
Demonstrates enumerate over a string, first-and-last retrieval, list and tuple slices, and out-of-range endpoints.
What it assumes
Assumes familiarity with Python sequences, loops, and function calls while teaching indexing and slicing distinctions directly.
What you can do after
Apply it via Python brackets, slices, negative positions, and enumerate to retrieve or label sequence data.
How it connects
Connects indexing with sequences, slicing, iteration, enumerate, tuples, lists, and strings.

Also explained in

Compare how 15 books explain indexing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.