Menu

Python Slicing Explained
πŸ“°

Python Slicing Explained

DEV Community: htmlΒ·Khawaja Khurram (MAK)Β·9 days ago
#OXnlLQwT
#devto2#devto#dev#element#elements
Reading 0:00
15s threshold

πŸ“š This article was originally published on MAK Studio . Check out the full interactive lesson with live demos and code examples.

Home β€Ί

Courses β€Ί

Python β€Ί

Problems β€Ί

Slicing

🐍 Concept · 4 min read

Python slicing. Indices point between elements.

The a[start:stop:step] syntax is elegant once you understand the mental model. The key insight: indices point between elements, not at them. The start index is the boundary before the first element you want; the stop index is the boundary after the last. That's why a[1:4] is three elements, not four. Once you see the boundaries, 90% of slicing confusion disappears.

Short answer: a[start:stop:step] β€” start inclusive, stop exclusive, step defaults to 1. a[1:4] is elements 1, 2, 3. a[:] copies. a[-3:] is the last 3. a[::2] takes every other. a[::-1] reverses. Slicing returns a new sequence β€” it doesn't modify the original. Negative indices count from the end. Missing values default to the ends (or to 1 for step).…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.