Coding

Slicing in Python: Lists and Strings Explained with Examples

Slicing in Python takes part of a sequence with the syntax sequence[start:stop:step], where start is included, stop is excluded and step is optional. It works the same way on lists, strings and tuples, and it always returns a new object of the same type.

nums = [10, 20, 30, 40, 50, 60, 70]
nums[1:4]    # [20, 30, 40]
nums[::-1]   # [70, 60, 50, 40, 30, 20, 10]

All outputs in this article are example output, worked out from the rules in the Python documentation. You can paste any snippet into a Python prompt to check it.

How the start:stop:step syntax works

Indexes count from 0. A slice picks every item whose index k satisfies start <= k < stop. The stop index is never part of the result, which looks odd at first but has a useful consequence: items[:i] + items[i:] always rebuilds the original sequence, and stop - start is the length of the result (when the slice is in range and the step is 1).

The Python documentation defines the defaults for omitted values:

  • If start is omitted or None, it is 0.
  • If stop is omitted or None, it is len(s).
  • If step is omitted or None, it is 1.

With nums = [10, 20, 30, 40, 50, 60, 70]:

SliceResult (example output)Meaning
nums[1:4][20, 30, 40]positions 1, 2, 3
nums[:3][10, 20, 30]the first 3 items
nums[4:][50, 60, 70]from position 4 to the end
nums[:][10, 20, 30, 40, 50, 60, 70]a new list with all items
nums[::2][10, 30, 50, 70]every second item
nums[1::2][20, 40, 60]every second item, starting at position 1

How negative indexes work in a slice

A negative index counts from the end. The docs state that if i or j is negative, len(s) + i or len(s) + j is substituted. For a list of 7 items, -1 means position 6 and -3 means position 4.

nums[-3:]    # [50, 60, 70]   last three items
nums[:-1]    # [10, 20, 30, 40, 50, 60]   everything except the last
nums[-4:-1]  # [40, 50, 60]

There is one trap. The documentation notes that -0 is still 0. So nums[:-0] means nums[:0] and returns an empty list, not the whole list. If the number of items to drop comes from a variable, nums[:-n] breaks when n is 0. Write nums[:len(nums) - n] in that case.

Slicing a string

A string is a sequence of characters, so the same rules apply, and the result is a new string. These examples come from the official tutorial, using word = 'Python':

word[0:2]    # 'Py'
word[2:5]    # 'tho'
word[:2]     # 'Py'
word[4:]     # 'on'
word[-2:]    # 'on'

Strings are immutable, so you cannot assign to a slice. Both of these fail:

>>> word[0] = 'J'
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
TypeError: 'str' object does not support item assignment

Build a new string from pieces instead: 'J' + word[1:] gives 'Jython', and word[:2] + 'py' gives 'Pypy'.

Slices count characters, not bytes. For a bytes object they count bytes. If you are checking how many items a sequence has before slicing, see how to count items in a list and a string in Python.

What happens when a slice goes out of range

Slices do not raise IndexError. Python clips the bounds instead. Per the documentation, a bound above len(s) becomes len(s), a bound below -len(s) becomes 0, and if the start is greater than or equal to the stop the result is empty.

nums[2:100]   # [30, 40, 50, 60, 70]
nums[100:]    # []
nums[-100:2]  # [10, 20]
nums[5:2]     # []

Single-item access is stricter. word[42] on a 6-character string raises IndexError: string index out of range, while word[42:] quietly returns ''. That quietness is convenient for things like "first 80 characters of a title" (title[:80] works whether the title has 5 or 500 characters), but it can also hide an off-by-one bug, because nothing tells you the slice came back short.

How to reverse and skip with a step

A negative step walks backwards. The documentation defines the indexes as i, i+k, i+2*k and so on, stopping before j. When the step is negative, omitted start and stop swap ends: the default start becomes the last item and the default stop goes past the first.

nums[::-1]     # [70, 60, 50, 40, 30, 20, 10]
nums[5:1:-2]   # [60, 40]   positions 5 and 3, stops before 1
"slicing"[::-1]  # 'gnicils'
"slicing"[::2]   # 'siig'

The step cannot be zero. nums[::0] raises ValueError: slice step cannot be zero (the docs only say the step "cannot be zero"; the exception name and message here are what CPython prints).

Reversing with [::-1] gives a quick palindrome check for strings: word == word[::-1]. For lists you only need to loop over, reversed(nums) returns an iterator and does not build a second list.

Slice assignment and deletion on lists

Lists are mutable, so a slice can sit on the left side of an assignment. The right side must be iterable, and the list can grow or shrink. This example is from the official tutorial:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = []
>>> letters
[]

Replacing with a shorter or longer list changes the length. del letters[1:3] removes a range without assigning anything.

The exception is an extended slice, one with a step other than 1. The documentation says the replacement must then have the same length as the slice it replaces. Assigning two values to a four-item slice fails:

>>> nums[::2] = [0, 0]
ValueError: attempt to assign sequence of size 2 to extended slice of size 4

Give it exactly four values, nums[::2] = [0, 0, 0, 0], and every other item is replaced.

Slicing makes a shallow copy

A list slice is a new list. Changing the new list does not change the original, as the tutorial shows with correct_rgba = rgba[:]. The docs also say list.copy() is equivalent to sequence[:]. The copy is shallow, though: it holds references to the same item objects. With nested lists, the inner lists are shared:

grid = [[1, 2], [3, 4]]
copy = grid[:]
copy[0].append(9)
print(grid)   # [[1, 2, 9], [3, 4]]

If you need independent inner lists, use copy.deepcopy() from the standard library. For flat lists of numbers or strings, [:] is enough. To build a new list by transforming or filtering items rather than selecting a range, a comprehension is the better fit: see Python list comprehension.

Reusing a slice with the slice() object

Slice syntax creates a slice object behind the scenes. You can build one yourself with slice(start, stop, step) and reuse it, which helps when the same range applies to several sequences, such as the columns of a fixed-width record:

first_three = slice(0, 3)
nums[first_three]        # [10, 20, 30]
"slicing"[first_three]   # 'sli'

The built-in functions reference says slice(start, stop, step) represents the indexes of range(start, stop, step), and that its start and step default to None. If you want a lazy version that returns an iterator instead of a new list, the same page points to itertools.islice().

Slicing tuples

Tuples support the same syntax and return a tuple: (1, 2, 3, 4)[1:3] is (2, 3). Because tuples are immutable, you cannot assign to a slice, the same as with strings. More on that type is in Python tuples explained.

If a slice returns something unexpected

  • Empty result when you expected items. Check that start is less than stop for a positive step, or greater than stop for a negative step. nums[5:2] is empty, nums[5:2:-1] is [60, 50, 40].
  • One item too few. The stop index is excluded. To include position 4, write stop=5.
  • Whole list when you wanted none. Check for [:-n] with n = 0, as described above.
  • The original list changed through a copy. The items are shared. Nested lists need copy.deepcopy().

Frequently asked questions

Does slicing in Python include the stop index?
No. The start index is included and the stop index is excluded, so items[2:5] returns the items at positions 2, 3 and 4. This is why items[:i] + items[i:] always gives back the original sequence.
Why does slicing past the end of a list not raise an error?
Python clips slice bounds to the sequence: an index above len(s) is treated as len(s), and one below -len(s) is treated as 0. Out-of-range slices return a shorter or empty result. Single-index access such as items[42] is different and raises IndexError.
Can I slice a string and change it in place?
No. Strings are immutable, so word[2:] = 'py' raises TypeError: 'str' object does not support item assignment. Build a new string instead, for example word[:2] + 'py'.
Does a slice copy the list?
A list slice returns a new list holding the same item objects, which is a shallow copy. The Python docs say list.copy() is equivalent to items[:]. Nested lists inside it are shared with the original, not duplicated.

Sources