Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 149 ยท Data Structures

Slicing

Learn Python slicing with start:stop:step. Take parts of lists and strings, use negative indexes and steps, reverse with [::-1] and replace sections with slice assignment.

Indexing gives you one item from a sequence: colors[0], word[-1]. Very often you want a piece instead: the first three results, the last five log lines, every other row, a string without its first character. Python handles all of these with one compact syntax called slicing.

A slice looks like an index with colons inside the brackets, items[start:stop:step]. It works the same way on lists, strings, tuples and ranges, and it never raises an IndexError, which makes it both powerful and forgiving. In this lesson you'll learn the three parts of a slice, how negative values behave, how to reverse a sequence, and how to replace or delete parts of a list with slice assignment.

start and stop

The basic form is sequence[start:stop]. It returns a new sequence containing the items from index start up to, but not including, index stop. That's the same rule as range().

Python Basic slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A helpful picture: think of indexes as pointing at the gaps between items, not at the items themselves. letters[1:4] cuts at gap 1 and gap 4 and gives you everything between the cuts.

TEXT
  | a | b | c | d | e | f | g |
  0   1   2   3   4   5   6   7
     [-----------)
        letters[1:4] -> b c d

With that picture, the length of a slice is simply stop - start, and two slices like [:3] and [3:] meet without overlapping.

Leaving out start or stop

Either value can be left out:

  • No start means "from the beginning": items[:3] is the first three items.
  • No stop means "to the end": items[3:] is everything from index 3 on.
  • Neither means "everything": items[:] is a full copy.
Python Open-ended slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

items[:n] and items[n:] always split a sequence into two parts that fit back together exactly, for any n. That's a pattern you'll use constantly, for example to separate a header row from data rows.

Negative indexes in slices

Negative numbers count from the end, just as with indexing. They're perfect for "the last few" or "all but the last":

Python Negative slice bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Slices never go out of range

Indexing past the end raises an error, but slicing quietly clips the bounds to fit the sequence. If the bounds leave nothing between them, you simply get an empty result.

Python Forgiving bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This makes items[:5] a safe way to say "at most five items", even when the list is shorter. Be careful, though: the same forgiveness can hide a bug, because a wrong index produces an empty or short result instead of an error.

The step

A third value, the step, says how far to move between items. It defaults to 1.

Python Steps, including negative ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With a negative step, slicing walks backward, so start should be the larger index:

  • Left-out start means "from the end", and left-out stop means "through the beginning".
  • digits[8:2:-2] begins at 8, moves left by 2 and stops before reaching 2: [8, 6, 4].
  • sequence[::-1] is the standard idiom for a reversed copy.

A step of 0 raises ValueError: slice step cannot be zero.

Tip: Combine slicing with steps sparingly. data[::2] reads well; data[-2:3:-3] makes readers stop and count. When a slice gets hard to understand, split it into two steps or add a comment with the expected result.

Slicing strings and tuples

Strings and tuples support exactly the same slicing, and since they're immutable, a slice is always a new string or tuple.

Python Slicing text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For fixed-format text such as codes, dates and IDs, slices are quick and readable. For anything with variable structure, string methods like split() or regular expressions are more robust.

Slice assignment: changing part of a list

Because lists are mutable, you can put a slice on the left side of =. Python removes the items in that slice and inserts the items from the right side, which doesn't have to be the same length.

Python Replacing, inserting and deleting with slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rules to remember:

  • With a step of 1, the slice and the new items can have different lengths; the list grows or shrinks to fit.
  • With any other step (an extended slice), the lengths must match exactly, or Python raises a ValueError.
  • del items[start:stop] deletes a range of items.
  • items[:] = new_values replaces the contents while keeping the same list object, so every other variable referring to that list sees the change. Plain items = new_values would point the name at a new list instead.

Slice assignment only works on mutable sequences. Trying it on a string raises TypeError, because strings can't be changed; build a new string from slices instead.

Slice objects

Behind the scenes, items[1:5:2] creates a slice object and passes it to the sequence. You can create one yourself with slice(start, stop, step) and give it a name, which helps when the same cut is used in several places:

Python
year_part = slice(4, 8)
codes = ["ORD-2026-00417", "ORD-2025-00090"]
for c in codes:
    print(c[year_part])     # 2026, 2025

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is [10, 20, 30, 40, 50][1:3]?

    The slice starts at index 1 (20) and stops before index 3, so it contains items 1 and 2.
  2. 2. Which expression gives the last two characters of s = "python"?

    s[-2:] starts two from the end and runs to the end, giving "on". s[:-2] is everything except the last two.
  3. 3. What does [1, 2, 3][5:9] return?

    Slices clip their bounds instead of raising errors. Nothing lies between 5 and 9 here, so the result is an empty list.
  4. 4. What is "abcdef"[::-2]?

    A negative step walks backward from the end, taking every second character - f, d, b.
  5. 5. After x = [1, 2, 3, 4] and x[1:3] = [9], what is x?

    The two items in the slice (2 and 3) are replaced by the single item 9, so the list shrinks by one.

Summary

  • seq[start:stop] returns a new sequence from start up to, but not including, stop; its length is stop - start.
  • Leave out start for "from the beginning", stop for "to the end", or both (seq[:]) for a copy.
  • Negative bounds count from the end: seq[-3:] is the last three, seq[:-1] all but the last.
  • Slicing clips out-of-range bounds instead of raising errors.
  • The step picks every nth item; a negative step walks backward, and seq[::-1] reverses.
  • Slicing works the same on lists, strings, tuples and ranges.
  • On lists, slice assignment and del seq[a:b] replace, insert or delete whole sections in place.

Next: List Comprehensions, where you'll build new lists from existing data in a single readable line.