Skip to main content

Slicing Deep Dive

Slicing is one of the most useful syntax features in Python and one worth getting familiar with early. It can not only extract subsequences but also reverse, step, and shallow-copy. Many of these patterns become second nature with practice.

Basic Syntax

sequence[start:stop:step]
  • start: Start position, inclusive
  • stop: End position, exclusive
  • step: Step size

Most Common Patterns

nums = [0, 1, 2, 3, 4, 5]

print(nums[1:4]) # [1, 2, 3]
print(nums[:3]) # [0, 1, 2]
print(nums[3:]) # [3, 4, 5]
print(nums[::2]) # [0, 2, 4]
print(nums[::-1]) # [5, 4, 3, 2, 1, 0]

Negative Indexing

text = "abcdef"

print(text[-1]) # f
print(text[-3:]) # def

Negative indexing counts from the end, making it great for handling "the last few elements".

Slicing isn't just for reading — you can assign to slices too

nums = [0, 1, 2, 3, 4, 5]
nums[1:4] = [10, 20, 30]
print(nums)

You can also delete a segment:

del nums[2:4]

Common Uses

1. Shallow copy a list

copied = nums[:]

2. Reverse a sequence

reversed_text = text[::-1]

3. Take every k-th element

evens = nums[::2]

An easily overlooked point

Slices usually return new objects, but whether they're "completely independent" depends on whether the elements in the sequence themselves are mutable. For more specific examples, see:

Quick-reference cheat sheet

  • [:n]: First n elements
  • [n:]: From n to the end
  • [-n:]: Last n elements
  • [::k]: Every k-th element
  • [::-1]: Reverse