liveBook · Manning

Slicing

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

Slicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.

Slicing selects a range from a Python string or list with [start:stop]. Indexing starts at 0, start defaults to the beginning, stop defaults to the end, and stop is excluded. section 2.1.7 section 3.3.4

Use slices to:

Rebuilding an immutable string

Strings cannot be changed by assigning to one position. Build a replacement instead: with i = 13, text[:i] gives the part before the position and text[i+1:] gives the part after it; combine them with a new character: text = text[:i] + new_char + text[i+1:]. section 10.3.1

Extracting and shuffling a word’s middle

For word = 'worry', word[1:-1] produces 'orr'. Convert that slice to a list before calling random.shuffle(), because strings cannot be modified in place; then combine the first, shuffled middle, and last parts. section 16.1.4

>>> word = 'narwhal'
>>> word[0]
'n'

You can index into a literal string value too:

>>> 'narwhal'[0]
'n'

Because the index values start with 0, that means the last index is one less than the length of the string, which is often confusing. The length of “narwhal” is 7, but the last character is found at index 6:

>>> word[6]
'l'

You can also use negative index numbers to count backwards from the end, so the last index is also -1:

>>> word[-1]
'l'

You can use slice notation [start:stop] to get a range of characters. Both start and stop are optional. The default value for start is 0 (the beginning of the string), and the stop value is not inclusive:

>>> word[:3]
'nar'

Inspect the REPL examples for zero-based indexing, negative indexes, omitted boundaries, and the non-inclusive stop position. section 2.1.7

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains zero-based indexes, omitted boundaries, excluded stops, negative indexes, and immutable-string workarounds, but not tensor-specific slicing.
Examples
Demonstrates prefixes, suffixes, list subranges, string replacement, verse gifts, word stemming, and scrambled word middles.
What it assumes
Assumes familiarity with Python sequences and indexes while teaching zero-based positions, boundaries, and string immutability through examples.
What you can do after
Apply it via Python slice notation to select subranges and reconstruct strings without direct character assignment.
How it connects
Connects slicing with indexing, strings, lists, immutability, list mutability, reversed(), and random.shuffle().

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.