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
- Strings, lists, tuples — and the same idea in NumPy and pandas.
- "The last three items", "every other element", "the string backwards".
- Making a quick copy of a list:
new = old[:].
What it does
It returns a new sub-sequence: the elements from start up to — but not including — stop, 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 uselist.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
- Strings, Listen, Tupel — und dieselbe Idee in NumPy und pandas.
- "Die letzten drei Elemente", "jedes zweite Element", "der String rückwärts".
- Schnell eine Kopie einer Liste machen:
new = old[:].
Was es tut
Es liefert eine neue Teilsequenz: die Elemente von start bis — aber ohne — stop, 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 mitlist.reverse().