liveBook · Manning

Slicing

As explained in Python Workout: 50 ten-minute exercises

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

When a program needs part of a string, list, or tuple, slicing retrieves a sub-sequence with compact index notation. The form sequence[start:stop:step] selects elements from start, stops before stop, and optionally advances by step. Omitting boundaries means starting at the beginning or continuing to the end. section 2.3 section 3.2

Use slicing to express common sequence operations directly:

  • s[2:6] retrieves positions 2 through 5; s[2:6:2] takes every second element. section 2.3
  • s[::2] selects every other element from the whole sequence. section 2.3
  • items[1:] iterates over everything after the first element, making it useful when the first value is handled separately. section 3.7
  • Slices tolerate bounds beyond the sequence, returning the available portion or an empty sequence; individual indexes instead raise an IndexError. section 3.2
  • A slice preserves the sequence type: slicing a list returns a list, and slicing a tuple returns a tuple. section 3.2

Selecting and reusing sequence parts

s = 'abcdefgh'\nprint(s[2:6]) # 'cdef'\nprint(s[2:6:2]) # 'ce'\nprint(s[::2]) # 'aceg'\n\ndef firstlast(sequence):\n return sequence[0] + sequence[-1]\n\nt1 = ('a', 'b', 'c')\nprint(firstlast(t1)) # ('a', 'c') is not produced by this expression; the operation combines elements according to their types\n\nFor accumulation, assign items[0] as the initial value and loop over items[1:], avoiding an artificial starting value of zero. A one-element input makes items[1:] empty, so the loop simply runs zero times. section 2.3 section 3.2 section 3.7

s = 'abcdefgh'
print(s[2:6])    #1

Run the compact string example to observe an ordinary range slice and its exclusive upper bound. section 2.3

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains bounds, steps, omitted indexes, type preservation, and forgiving ranges, but does not descend into implementation internals.
Examples
Uses alphabetic strings, first-and-last sequence functions, accumulation with items[1:], Pig Latin, and hexadecimal reversal.
What it assumes
Assumes familiarity with Python sequences and numeric indexing while clarifying how slices differ from individual element retrieval.
What you can do after
Apply Python slice syntax to select ranges, steps, prefixes, suffixes, and remaining sequence elements in runnable code.
How it connects
Connects slicing with sequence indexing, strings, lists, tuples, iteration, searching, and accumulation.

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.