Python Indexing and Slicing

By Seokhyeon Byun 3 min read

Note: This post is based on my old programming study notes when I taught myself.

Sequence Operations

  • len(): Returns the number of items in a sequence. When the length of a sequence is $n$, the index set is 0~$n$-1

Indexing

# Indexing Example
a = "Life is too short"
print(a[0], a[5])    # L i
print(a[-1], a[-2])  # t r
  • The first index is 0
  • When processing indexes in reverse from the end, you can specify indexes like -1, -2, -3, etc.

Slicing

  • Function that cuts from start to just before end based on index
  • A[x:y:z] - x or more, less than y, z interval
  • B[n:] - from n index to the end
  • C[:m] - from beginning to (m-1)th index value
  • D[:] - from beginning to end

Examples

# Example 1
b = "20010331Rainy"
print(b[:8])   # '20010331' (still a string)
print(b[8:])   # 'Rainy'

# Example 2
c = "12345678"
print(c[::1])   # '12345678'
print(c[::2])   # '1357'
print(c[::-1])  # '87654321'
print(c[::-2])  # '8642'

Key Points

  • Index Range: For a sequence of length n, valid indexes are 0 to n-1
  • Negative Indexing: -1 refers to last element, -2 to second-to-last, etc.
  • Slicing Syntax: [start:stop:step]
    • start: inclusive starting position
    • stop: exclusive ending position
    • step: interval between elements
  • Default Values: Omitted values use defaults (0 for start, length for stop, 1 for step)
  • Reverse Slicing: Use negative step values to reverse direction

Advanced Slicing Techniques

Multi-dimensional Slicing

# Working with lists of lists
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

# Access specific row
first_row = matrix[0]       # [1, 2, 3, 4]
last_row = matrix[-1]       # [9, 10, 11, 12]

# Access specific element
element = matrix[1][2]      # 7 (row 1, column 2)

# Access column (requires list comprehension)
first_column = [row[0] for row in matrix]  # [1, 5, 9]

# Slice rows
first_two_rows = matrix[:2]  # [[1, 2, 3, 4], [5, 6, 7, 8]]

# Slice within rows
partial_rows = [row[1:3] for row in matrix]  # [[2, 3], [6, 7], [10, 11]]

String Slicing Patterns

text = "Programming Python"

# Extract words
words = text.split()        # ['Programming', 'Python']
first_word = text.split()[0]  # 'Programming'

# Extract substring between positions
middle = text[5:10]         # 'ammin'

# Extract every nth character
every_second = text[::2]    # 'PormigPto'
every_third = text[::3]     # 'PgmnPh'

# Extract first/last n characters
first_5 = text[:5]          # 'Progr'
last_5 = text[-5:]          # 'ython'

# Remove first/last n characters  
without_first_last = text[1:-1]  # 'rogramming Pytho'