Slicing with Step

The third slice argument, counting from the end, and why the stop index is never included.

Overview

The third slice argument, counting from the end, and why the stop index is never included.

In this guide
  1. The stop is excluded
  2. Negative indices count from the right
  3. The third value is the step
  4. Reversing three ways
  5. Slicing does not raise
  6. Copies, views and strings
  7. Assigning into a slice
  8. Step with a negative start and stop
  9. A worked example: the three arguments together
  10. Why a negative step reverses the roles
  11. Slice objects, and the syntax behind the colons
  12. Slicing is a protocol, not a list feature
  13. Idioms worth recognising on sight
  14. Choosing between an index and a slice
  15. Questions people ask about Slicing with Step
  16. Slicing with Step: recap in one screen

slicing.py

slicing.py Python 3
Output

                    

slicing_lists.py

slicing_lists.py Python 3
Output

                    

Worth knowing

[start:stop:step], and the stop is never included.
Negative indices count from the end: -1 is the last item.
[::-1] reverses. [:] copies.
Slicing out of range is silent; indexing out of range raises IndexError.

Slicing with Step: A Practical Guide

A slice takes a piece of a sequence using up to three numbers: where to start. Here To stop. How big a step to take. Two rules explain nearly all of its action.

The stop is excluded

s[2:5]

gives the items at positions 2, 3, and 4. This is the same rule as range. It has the same payoff: s[:3] and s[3:] split the sequence with no overlap and no gap. The length of s[a:b] is b - a.

Leave either end off and it means "from the beginning" or "to the end." Leave both off and s[:] is a copy of the whole sequence. That is the idiomatic way to shallow-copy a list.

Slicing works on any sequence type: lists, strings, tuples, and anything else that supports indexing. The syntax is always the same. The result is a new object of the same type. Slicing a list gives a list. Slicing a string gives a string. The original is never modified.

Negative indices count from the right. s[-1] is the last item. s[-2] is the second to last. This works in slices too: s[1:-1] gives everything except the first and last items. Negative indices save you from writing s[len(s) - 1] every time you need to reference the end of a sequence.

The step parameter adds a third number after a second colon. s[::2] takes every other item. s[1::2] takes every other item starting from position 1. The step can be negative: s[::-1] reverses the sequence. That is probably the most commonly used step value.

A negative step changes the direction of traversal. When the step is negative, the default start becomes the last item and the default stop becomes before the first item. s[4:1:-1] gives items at positions 4, 3, and 2, in that order. Getting the boundaries right with negative steps takes practice, and the best way to build intuition is to try small examples in the interpreter.

Slicing never raises an IndexError, even if the indices are out of range. Python silently clamps them to the sequence boundaries. s[0:100] on a five-element list gives all five elements without error. That is different from indexing, where s[100] raises an IndexError.

This page covers the basic slice syntax, negative indices, the step parameter, reversing with [::-1], and the boundary clamping behavior.

Negative indices count from the right

s[-1]    # last item
s[-3:]   # last three
s[:-2]   # everything except the last two

-1 is the last element, not "one before the start". Mixing the two rules is fine: s[2:-1] is "from index 2 to the second-to-last".

The third value is the step

s[::2]    # every second item
s[1::2]   # every second, starting at 1
s[::-1]   # reversed

[::-1] is the standard reverse idiom and worth storing as one symbol rather than parsing each time. A minus step walks backwards. Start and stop swap roles. Which is why s[5:2:-1] gives you a thing and s[2:5:-1] gives you nothing.

Reversing three ways

data[::-1] builds a new reversed list. reversed(data) returns a lazy iterator and copies nothing. data.reverse() reorders in place and returns None. The same trap as .sort().

Slicing does not raise

a[5:99] on a three-item list returns what exists, and a[99:] returns an empty list. No exception either way. That is convenient when you're taking "up to ten" of a thing and there might be fewer.

It's also a place bugs hide. An empty slice looks like legitimate data. A function that slices with a found index and returns nothing hasn't always worked right - it may have found the wrong index and been silently forgiven. When the index must be valid, index rather than slice, and let IndexError tell you.

Copies, views and strings

A slice of a list is a shallow copy: a new list holding the same objects. That is why b = a[:] is a copy idiom. Why changing b[0] = x leaves a alone while b[0].append(x) doesn't - the outer list is new, the items are shared.

A slice of a string is a new string. Strings are immutable and there's nothing else it could be. That makes s[::-1] a genuine copy in reverse, which matters only when the string is very large.

Assigning into a slice

Lists let you assign to a slice. The swap need not be the same length:

nums[1:3] = ["a", "b", "c"]     # two items become three
del nums[1:3]                   # or remove them entirely

This changes the list in place, including its length, and it's the one part of slicing that mutates rather than copies. It's worth knowing mainly so that you recognise it in other people's code, and because it shows why a[:] = b replaces the contents of a while a = b merely rebinds the name.

Step with a negative start and stop

Mixing a minus step with minus indices is where slices become write-only. a[-2::-1] is "start at the second-to-last, walk backwards to the beginning" - correct, and not obvious on sight. When a slice needs a comment, reversed() and an clear loop often say it better.

A worked example: the three arguments together

each rule on this page in one block, with the results printed rather than given:

s = "abcdefgh"

print(s[2:5])
print(s[-3:])
print(s[::2])
print(s[::-1])
print(s[5:2:-1])
print(s[2:99], repr(s[99:]))
cde
fgh
aceg
hgfedcba
fed
cdefgh ''

Read them in order. s[2:5] starts at 2 and stops before 5. s[-3:] counts from the right. s[::2] takes each second character from the whole string. s[::-1] reverses. s[5:2:-1] walks backwards from 5 down to but not including 2, which is where the exclusive stop starts feeling strange — the item at index 2 is missing from the result though 2 is written on the left of the colon.

The last line is the forgiveness: an end past the length is clamped, and a start past the length gives an empty string rather than an error.

Why a negative step reverses the roles

s[2:5:-1] returns nothing, and the reason is worth spelling out because it's the one part of slicing people store rather than understand.

A slice always moves from the start value towards the stop value, in the direction the step gives. With a plus step it moves right, so the start must be to the left of the stop. With a minus step it moves left, so the start must be to the *right* of the stop. s[2:5:-1] asks to begin at 2 and walk leftwards until it reaches 5. This It never will. So The result is empty right away.

That also shows the defaults. When the step is minus and you leave the ends off, the omitted start turns the end of the sequence and the omitted stop turns "past the beginning". Which is why s[::-1] gives you all reversed, including the first character. Writing s[::-1] and s[len(s):0:-1] aren't the same: the second stops before index 0 and drops the first character.

The hands-on consequence is that there's no way to write "reversed, ending at the very beginning" with an clear stop. The stop would have to be -1, and -1 already means the last item. Omitting it's the only way to say it, which is just why the idiom is [::-1] and not a thing more clear.

Slice objects, and the syntax behind the colons

The bracket syntax is shorthand. a[1:5:2] is a[slice(1, 5, 2)], and slice is an plain object you can build, store and pass around.

That is at times handy in its own right. Naming a slice you use again and again, HEADER = slice(0, 4), makes the call sites say what they mean. More often it's handy as an explanation. It's why a[1:5] and a[slice(1, 5)] behave the same way, why a class can support slicing by handling a slice in its __getitem__, and why the ellipsis and comma forms that NumPy uses are possible at all: a[1:5, ::2] passes a tuple of slices, which plain Python lists reject and NumPy arrays understand.

indices() on a slice object resolves it against a length, returning the concrete start, stop and step after clamping and minus-index conversion. slice(1, 99).indices(5) gives (1, 5, 1). This Is the math the forgiving action is built on, made visible.

Slicing is a protocol, not a list feature

All on this page works on any sequence, and knowing that is what makes the syntax worth learning properly rather than storing for lists.

Strings, tuples, bytes, bytearrays and range all slice with the same three numbers and the same rules, and each returns its own type — slicing a tuple gives a tuple, slicing a range gives a range, found rather than materialised. bytes slicing is how binary formats are parsed, taking a header, a length field and a payload by offset.

Beyond the builtins, any class can support it by handling a slice object in __getitem__, and the libraries that do have extended the idea a lot. NumPy accepts a tuple of slices, a[1:5, ::2], to take a rectangle out of a two-dimensional array, and its slices are *views* rather than copies — writing into one changes the first. This Is the opposite of the list action and a genuine trap when moving between them. pandas uses the same brackets with labels rather than spots in .loc. Here The stop is inclusive, breaking the one rule you had learned to lean on.

The lesson isn't to distrust slicing but to check two things when a new type supports it: whether the result is a copy or a view, and whether the stop is excluded. Those two answers differ across the ecosystem and all else stays the same.

Idioms worth recognising on sight

A handful of slices appear often enough to read as single symbols rather than as math. Knowing them saves parsing the numbers each time.

a[::-1] reverses. a[:] copies a list, and is also the left-hand side of a[:] = b, which replaces the contents of a in place rather than rebinding the name — the difference that matters when someone else holds a ref to a.

a[:n] and a[n:] are "the first n" and "all after the first n", and together they cover the whole sequence just once. a[-n:] is the last n, and a[:-n] is all except the last n. This Is how you drop a known suffix without finding a length.

a[::n] takes each nth item, and a[i::n] takes each nth starting from i — the pair of them is how you deinterleave two sequences that were interleaved into one, with a[::2] and a[1::2].

s[:0] is an empty sequence of the same type, at times handy as a starting value when you need "an empty one of what this is" without naming the type.

Choosing between an index and a slice

The two look similar and they fail differently. This Is the basis for choosing between them.

a[i] asserts that spot i exists. If it doesn't, you get an IndexError naming the problem at the line that caused it. a[i:i+1] makes no such assertion: out of range, it hands back an empty sequence and the program carries on with nothing.

So the choice is about whether lack is a bug. Taking the first item of a list that is documented to be non-empty should be a[0], because an empty list means a thing upstream is wrong and you want to hear about it. Taking "up to ten results" from a list that might have three should be a[:10], because having fewer is expected and the clamping is just right.

The mistake in one direction is a crash on data that was always going to be short. The mistake in the other is a silent empty result that gets reported as zero, saved as an empty file, or treated as "no matches found" — and those are much harder to trace, because there's no error to start from.

One hands-on consequence: when a slice with found bounds returns nothing, don't assume the data was empty. Print the bounds. An off-by-one that makes a[5:5] looks the same in the output to a list that truly had nothing to give.

Questions people ask about Slicing with Step

Is a[:] the same as a.copy()? For a list, yes — both are shallow copies. For a string it returns the same object, since there's nothing to copy.

Why does a[::-1] work on strings and a.reverse() not? reverse is a list method that mutates, and strings can't be mutated.

What is the difference between a[::-1] and reversed(a)? The slice builds a new sequence. reversed returns a lazy iterator and copies nothing.

Can I slice a gen? No. Use itertools.islice, which takes the same start, stop and step but can't go backwards.

Does slicing a tuple give a tuple? Yes. A slice returns the same type as the thing sliced, for the built-in sequences.

How do I take each nth item starting from the end? a[::-n] — the minus step both reverses and strides.

Why is a[1:3] = [1, 2, 3] allowed? Because slice set replaces a section and may change the length. It's the mutating counterpart of the copying slice.

Does slicing a list of objects copy the objects? No. The new list holds the same objects. This Is the shallow-copy action from elsewhere in the track.

Can the step be zero? No. a[::0] raises ValueError, because a step of zero would never advance and the slice would never end.

Is a[0:len(a)] the same as a[:]? Yes, and the shorter form is preferred — it doesn't have to find a length that the slice already handles.

Slicing with Step: recap in one screen

  • Three numbers: start, stop, step. The stop is always excluded, just as in range.
  • Minus indices count from the right, and can be mixed freely with plus ones.
  • A minus step swaps the roles of start and stop. This Is why s[2:5:-1] is empty and s[::-1] reverses.
  • Slicing clamps rather than raising. This Is convenient and at times hides a wrong index.
  • A slice copies. Assigning into a slice mutates, and can change the length.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What is `'abcdef'[1:4]`?

  2. What does `s[::-1]` do?

  3. `s[99]` raises IndexError but `s[2:99]` does not. Why?

Cheat sheet

Slicing with Step

Slice sequences with start, stop and step, reverse them with [::-1], and see how negative indices count from the end.

PYTHON · vizlearn.in/python/slicing_step_negatives.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.