liveBook · Manning

Square brackets

As explained in Get Programming: Learn to code with Python

Square bracket notation is Python syntax that places an index or slice specification inside brackets to access part of a sequence.

Square brackets let you create lists and access particular parts of sequences. Put an integer index inside the brackets to retrieve one item or character; use a colon-based slice to retrieve a group of characters. section 25.2 section 7.2

Reading a grocery list

grocery = ["milk", "eggs", "bread"] print(grocery[0]) print(grocery[1]) print(grocery[2]) Python starts counting at 0, so these lines print milk, eggs, and bread. The list has three elements, and index 3 is beyond its limits. section 25.2

Remember these rules:

  • The first element or character is at index 0. section 25.2 section 7.2
  • Negative indexes count backward; the last character in a string is at index -1. section 7.2
  • A slice uses the form [start_index:stop_index:step] to extract part of a string. section 7.2
  • An invalid list index raises an IndexError because it is outside the list. section 25.2
Figure 7.1. The string “Python rules!” and the index of each character. The first row shows indexing with positive integers, and the second row shows indexing with negative integers.

Use the character-index diagram to see positive and negative positions arranged around the string “Python rules!”. section 7.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines indexing, negative positions, slicing syntax, and out-of-range errors through short examples and checks.
Examples
Uses grocery lists, “Python rules!”, student records, character indexes, and quick-check expressions.
What it assumes
Assumes basic Python expressions and variables while teaching zero-based positions and bracket syntax explicitly.
What you can do after
Apply it in Python to create lists, retrieve sequence items, slice strings, and recognize invalid list indexes.
How it connects
Connects square brackets with lists, strings, tuples, indexing, and slicing.

Also explained in

Compare how 2 books explain square brackets →

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.