Python Tutorial 0/52 lessons ~6 min read Lesson 22

    Slicing & Indexing

    Slicing with [start:stop:step] works on any sequence: list, tuple, string.

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Slicing with [start:stop:step] works on any sequence: list, tuple, string. Negative indices count from the end.

    Understanding the topic

    Core concepts to understand:

    • xs[1:4] — items 1..3.
    • xs[::-1] — reverse.
    • xs[::2] — every other.
    • Slicing copies; reassignment slices replace in place.

    Syntax reference

    Visual flow / code:

    python
    xs = [0, 1, 2, 3, 4, 5]
    xs[1:4] # [1, 2, 3]
    xs[:3] # [0, 1, 2]
    xs[-2:] # [4, 5]
    xs[::-1] # reversed
    xs[::2] # [0, 2, 4]
    # Replace a slice
    xs[1:3] = [10, 20, 30] # grows the list
    # Strings slice the same way
    "abcdef"[1:4] # 'bcd'

    Execution workflow

    1Slicing & Indexing Workflow
    1 / 4

    xs[1:4]

    items 1..3.

    Real-world use

    Slicing is one of Python's most loved features — it makes data wrangling code read like English: data[-100:], signal[::2].

    Best practices

    • Use slicing for copies: new = old[:].
    • Step -1 reverses any sequence.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat does <code>xs[::-1]</code> do?+

    Answer

    It returns a new list (or string or tuple) with the elements in reverse order, since the step of -1 walks backwards with default start and stop. It is a shallow copy for lists. For a lazy alternative that does not copy, use reversed(xs).
    2BeginnerQuestionSlice vs index — what's the difference?+

    Answer

    An index like xs[i] returns a single element and raises IndexError if out of range. A slice like xs[i:j] returns a new sequence of the same type and never raises for out-of-range bounds, clamping them instead. Slices use a half-open range, so the stop is excluded.

    Follow-up

    What does xs[100:] return on a short list?
    3IntermediateQuestionSlice assignment behavior?+

    Answer

    Slice assignment replaces the selected part of a mutable sequence with the elements of an iterable, and the lengths do not need to match, so the list can grow or shrink: xs[1:3] = [9]. With an extended slice (a step other than 1) the lengths must match or ValueError is raised. Strings and tuples do not support it because they are immutable.

    Follow-up

    What does xs[:] = [] do?

    Summary

    In summary: [start:stop:step] is universal. Negative indices count from end.

    Ready to mark this lesson complete?Track your journey across the entire course.