Slicing
PronunciationSLY-sing
Definition
Slicing takes a part of a sequence, such as a list or a string, using the form [start:stop:step]. The stop position is not included.
Where you hear it
In Python tutorials, string and list manipulation, and interview exercises such as reversing a string.
Examples
names[1:3]returns the second and third items.text[::-1]reverses the string.The slice items[1:4] takes the second, third and fourth elements.
Common mistake
Forgetting that the stop index is excluded, so [0:3] gives three items, not four.
Don't confuse with
Indexing. An index like items[2] returns one element; a slice like items[2:3] returns a new sequence.
Say it at work
- In a meeting or chat
Just slice the first ten rows instead of looping through everything.
- In an email or ticket
A slice returns a copy, so the original list stays unchanged.
Keep exploring
More in Programming Fundamentals