🐍

Slicing and Advanced Indexing

Programare Python Intermediate 5 min read

Slicing and Advanced Indexing

Syntax

sequence[start:stop:step]
  • start: Beginning index (inclusive), default 0
  • stop: Ending index (exclusive), default len()
  • step: Step size, default 1

Examples

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

nums[2:5]     # [2, 3, 4]
nums[:4]      # [0, 1, 2, 3]
nums[6:]      # [6, 7, 8, 9]
nums[::2]     # [0, 2, 4, 6, 8]
nums[::-1]    # [9, 8, 7, ..., 0] - reversed
nums[-3:]     # [7, 8, 9] - last 3

Slice Assignment

nums[2:4] = [20, 30]      # Replace
nums[2:2] = [10]          # Insert
nums[2:5] = []            # Delete

Key Points

  • stop is exclusive
  • [::-1] reverses sequence
  • Negative indices count from end
  • Slicing doesn’t raise IndexError for invalid indices
  • Slicing creates a shallow copy

📚 Related Articles