Concepts / String Slicing

String Slicing

List slicing uses the syntax t[start:stop] to extract a portion of a list, where start is included and stop is excluded.

  • Programming
Interactive lab

Try it: Indexing and Slicing

How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.

How it works

  1. Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
  2. An index outside the string raises IndexError.
  3. A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
  4. A negative step walks backwards; a step of 0 is a ValueError.

Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).

Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.

Educational simulation

Loading the simulation…

The Boundary Rule

List slicing extracts a portion of a list with the syntax t[start:stop]. The start index is included, but the stop index is excluded. This means that t[1:3] selects the elements at indices 1 and 2, not the element at index 3. Learning to identify those two boundaries is the central skill in slicing.

What do you think happens?

Given values = ['a', 'b', 'c', 'd'], what does values[1:3] return?

  • ['a', 'b']

  • ['b', 'c']

  • ['b', 'c', 'd']

  • ['c', 'd']

Reveal answer
Answer:

['b', 'c']

Index 1 is included and index 3 is excluded, so the selected indices are 1 and 2.

Mapping Boundaries to Elements

index 0'a't[1:3]['b', 'c']index 1'b'index 2'c'index 3'd'includedincluded
Which elements are included when the slice uses start index 1 and stop index 3?

Read a slice as a range of index positions. For t[1:3], begin at index 1, include that element, and continue up to but not including index 3. The resulting list therefore contains two elements: the values stored at indices 1 and 2. The stop number describes where selection ends; it is not another included position.

Worked example

Selecting a Middle Portion

Determine the result of letters[2:5] when letters = ['a', 'b', 'c', 'd', 'e', 'f'].

  1. 1
    Read the start

    The start index is 2, so the element at index 2, 'c', is included.

  2. 2
    Read the stop

    The stop index is 5, so the element at index 5, 'f', is excluded.

  3. 3
    List the selected indices

    The included indices are 2, 3, and 4.

  4. 4
    Translate indices to values

    Indices 2, 3, and 4 contain 'c', 'd', and 'e'.

Result

letters[2:5] produces ['c', 'd', 'e'].

Shortcuts with Omitted Indices

A slice does not require both boundary numbers. In t[:n], the omitted start means selection begins at the beginning of the list, and the result contains the first n elements. In t[n:], the omitted stop means selection continues from index n through the end of the list. In t[:], both boundaries are omitted, so the result is a copy of the entire list.

index 0'a't[:2]first two elementsindex 1'b't[2:]index 2 onwardindex 2'c't[:]entire listindex 3'd'selectedselectedselectedselectedselectedselectedselectedselected
What portion of a list is selected when the start index, stop index, or both indices are omitted?
python
Output
first_two is ['a', 'b']
from_index_two is ['c', 'd']
copy_of_values is ['a', 'b', 'c', 'd']

Replacing a Slice

Slice assignment uses the form t[start:stop] = new_list. Instead of producing a separate sublist, this operation replaces the selected portion of the original list. The replacement list can have a different length from the selected slice. A longer replacement makes the original list grow, while a shorter replacement makes it shrink. Elements outside the selected slice remain unchanged.

'a'index 0'a'index 0'b', 'c't[1:3]'x', 'y', 'z'replacement'd', 'e', 'f'indices 3 to 5'd', 'e', 'f'shifted rightreplaced byshifted right
How does assigning a three-element list to a two-element slice change the original list?
Code walkthrough
letters = ['a', 'b', 'c', 'd', 'e', 'f']
letters[1:3] = ['x', 'y', 'z']
letters
  1. 1
    The original list contains six elements.
  2. 2
    The selected slice is ['b', 'c'] because index 1 is included and index 3 is excluded.
  3. 3
    The selected two elements are replaced by ['x', 'y', 'z'].
  4. 4
    The resulting list contains seven elements.
  • The slice letters[1:3] identifies the two elements at indices 1 and 2.
  • The replacement contains three elements, so the list grows by one element.
  • The elements after the slice remain in the list and shift to the right.
Output
['a', 'x', 'y', 'z', 'd', 'e', 'f']
Before
letters = ['a', 'b', 'c', 'd', 'e', 'f']

['a', 'b', 'c', 'd', 'e', 'f']

After
letters = ['a', 'b', 'c', 'd', 'e', 'f']
letters[1:3] = ['x', 'y', 'z']

['a', 'x', 'y', 'z', 'd', 'e', 'f']

Steps and Extended Slices

The full slice form is t[start:stop:step]. When the step is omitted, it defaults to 1, so every element between the boundaries is selected. A step of 2 selects every other element, and a step of 3 selects every third element. A negative step reverses the selection.

python
Output
every_other is ['a', 'c', 'e']
every_third is ['a', 'd']
reversed_values is ['f', 'e', 'd', 'c', 'b', 'a']

Mistakes Beginners Make

  • Common mistake

    Including the stop index in the result

    What it looks like

    Assuming values[1:3] includes indices 1, 2, and 3

    Why it fails

    The stop index is excluded from a slice.

    Do this instead

    Select the indices from the start through the position immediately before the stop.

  • Common mistake

    Treating t[:n] as a slice ending with index n

    What it looks like

    Expecting values[:2] to contain indices 0, 1, and 2

    Why it fails

    The omitted start begins at index 0, but the stop index 2 is still excluded.

    Do this instead

    Remember that values[:2] returns the first two elements.

  • Common mistake

    Expecting slice assignment to preserve list length

    What it looks like

    Assigning three replacement elements to values[1:3]

    Why it fails

    The selected slice has two elements, while the replacement has three, so the list grows.

    Do this instead

    Compare the lengths of the selected slice and replacement list to predict whether the original list grows or shrinks.

  • Common mistake

    Confusing extraction with modification

    What it looks like

    Reading values[1:3] and values[1:3] = ['x', 'y'] as if they performed the same operation

    Why it fails

    The first expression extracts a portion; the second replaces a portion of the original list.

    Do this instead

    Check which side of the assignment operator contains the slice.

Prediction Practice

MEDIUM

Before checking the results, predict each expression. Use the start-included and stop-excluded rule, then verify your predictions by running the code.

Hints
  • For values[1:4], list indices 1, 2, and 3.
  • For values[:3], begin at index 0 and stop before index 3.
  • For values[3:], continue from index 3 through the end.
  • For slice assignment, compare the number of selected elements with the number of replacement elements.
python
Output
first_result is ['b', 'c', 'd']
second_result is ['a', 'b', 'c']
third_result is ['d', 'e']
final_result is ['a', 'x', 'd', 'e']
Worked example

Checking a Shrinking Assignment

Predict the result after values[1:3] = ['x'] when values = ['a', 'b', 'c', 'd', 'e'].

  1. 1
    Identify the selected slice

    Indices 1 and 2 are selected, so the original elements are 'b' and 'c'.

  2. 2
    Compare lengths

    Two elements are selected, but the replacement list contains one element.

  3. 3
    Apply the replacement

    The two selected elements are replaced by the single element 'x'.

  4. 4
    Keep the other elements

    The elements 'a', 'd', and 'e' remain, with 'd' and 'e' following the replacement.

Result

The modified list is ['a', 'x', 'd', 'e']; it has shrunk by one element.

Key Takeaways

  1. 1
    Use t[start:stop] to select a portion of a list.
  2. 2
    The start index is included and the stop index is excluded.
  3. 3
    Use t[:n] for the first n elements, t[n:] for index n onward, and t[:] for a copy of the entire list.
  4. 4
    Use t[start:stop] = new_list to replace multiple elements in the original list.
  5. 5
    A replacement list can make the original list grow or shrink, and t[start:stop:step] can select elements at intervals.

At a glance

  • A slice includes its start index but excludes its stop index.
  • Omitting the start selects from the beginning, omitting the stop selects through the end, and omitting both creates a copy of the entire list.
  • Slice assignment changes the original list and can replace a selected slice with a shorter or longer list.
  • The optional step controls the interval between selected elements, and a negative step reverses the selection.
  • Predict the selected indices before running code, then compare the prediction with Python's result.

Related concepts

More concepts starting with S