← CS Lab Programming Foundations / Python Slicing Open standalone ↗

Slicing grabs a chunk of a sequence without writing a loop. The syntax is seq[start:stop:step] — give it where to begin, where to end, and how big a stride to take.

Where you meet it

What it does

It returns a new sub-sequence: the elements from start up to — but not includingstop, taking every step-th one. The original is untouched.

A slice always hands you a new sequence — it never touches the original.

How it works

All three parts are optional. Their defaults: start = 0, stop = end, step = 1.

s = [0, 1, 2, 3, 4, 5]
s[1:4]    # [1, 2, 3]     from 1, up to (not incl.) 4
s[:3]     # [0, 1, 2]     start defaults to 0
s[3:]     # [3, 4, 5]     stop defaults to the end
s[-2:]    # [4, 5]        negative counts from the end
s[::2]    # [0, 2, 4]     every second element
s[::-1]   # [5, 4, 3, 2, 1, 0]   negative step → reversed

Indices out of range don't crash — they're clamped. s[1:99] just stops at the end.

Watch out

  • Stop is exclusive. s[0:3] gives 3 items, not 4 — the classic off-by-one.
  • A slice is a copy. Changing the slice never changes the original list (unlike s[0] = ...).
  • The copy is shallow — nested objects are shared, not duplicated.
  • s[::-1] is the idiomatic "reverse", but it builds a new sequence; for in-place use list.reverse().

Go deeper

Slicing schneidet ein Stück aus einer Sequenz — ohne Schleife. Die Syntax ist seq[start:stop:step]: wo es beginnt, wo es endet, und wie groß die Schrittweite ist.

Wo es vorkommt

Was es tut

Es liefert eine neue Teilsequenz: die Elemente von start bis — aber ohnestop, und nimmt jedes step-te. Das Original bleibt unberührt.

Ein Slice gibt dir immer eine neue Sequenz — das Original rührt es nie an.

Wie es funktioniert

Alle drei Teile sind optional. Ihre Defaults: start = 0, stop = Ende, step = 1.

s = [0, 1, 2, 3, 4, 5]
s[1:4]    # [1, 2, 3]     ab 1, bis (ohne) 4
s[:3]     # [0, 1, 2]     start ist standardmäßig 0
s[3:]     # [3, 4, 5]     stop ist standardmäßig das Ende
s[-2:]    # [4, 5]        negativ zählt vom Ende
s[::2]    # [0, 2, 4]     jedes zweite Element
s[::-1]   # [5, 4, 3, 2, 1, 0]   negativer step → rückwärts

Indizes außerhalb des Bereichs stürzen nicht ab — sie werden begrenzt. s[1:99] hört einfach am Ende auf.

Worauf achten

  • Stop ist exklusiv. s[0:3] liefert 3 Elemente, nicht 4 — der klassische Off-by-one.
  • Ein Slice ist eine Kopie. Den Slice zu ändern ändert nie die Originalliste (anders als s[0] = ...).
  • Die Kopie ist flach — verschachtelte Objekte werden geteilt, nicht dupliziert.
  • s[::-1] ist das idiomatische "umkehren", baut aber eine neue Sequenz; in-place geht mit list.reverse().

Mehr dazu

Next up
Programming FoundationsPython Data Structures Programming FoundationsPython Mutability & References All concepts →