slice Objects Name Reusable Slicing Bounds

Slices clamp out-of-range bounds instead of raising, negative indices count from the end, slice objects are reusable by name, slice assignment resizes lists.

PythonData Integrity

Code

pythonsnippet
28 lines
# 负索引从末尾倒数;步长为负则反向遍历
letters = ["a", "b", "c", "d", "e"]
print("letters[1:4]  :", letters[1:4])
print("letters[-2:]  :", letters[-2:])
print("letters[::2]  :", letters[::2])
print("letters[::-1] :", letters[::-1])

# 切片越界被钳制不抛错,索引访问才会抛 IndexError
print("letters[:99]  :", letters[:99])
try:
    letters[99]
except IndexError as exc:
    print("letters[99]   : IndexError", exc)

# 切片对象可复用、可命名:坐标或列布局写一次到处用
FIRST_THREE = slice(0, 3)
LAST_TWO = slice(-2, None)
print("FIRST_THREE   :", letters[FIRST_THREE])
print("LAST_TWO      :", letters[LAST_TWO])

# 切片赋值可以一次替换、插入或删除一段,长度不必相等
scores = [1, 2, 3, 4, 5]
scores[1:3] = [20, 30, 35]  # 2 个元素换成 3 个
print("replaced      :", scores)
scores[1:1] = ["start"]  # 空切片做插入
print("inserted      :", scores)
del scores[-2:]  # 删除尾部一段
print("deleted tail  :", scores)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

letters[1:4]  : ['b', 'c', 'd']
letters[-2:]  : ['d', 'e']
letters[::2]  : ['a', 'c', 'e']
letters[::-1] : ['e', 'd', 'c', 'b', 'a']
letters[:99]  : ['a', 'b', 'c', 'd', 'e']
letters[99]   : IndexError list index out of range
FIRST_THREE   : ['a', 'b', 'c']
LAST_TWO      : ['d', 'e']
replaced      : [1, 20, 30, 35, 4, 5]
inserted      : [1, 'start', 20, 30, 35, 4, 5]
deleted tail  : [1, 'start', 20, 30, 35]

How the snippet works

The file’s state is a handful of top-level bindings: letters, scores.

What to watch for

  • Built-in APIs only, so there is no supply chain to vet.

Using it

The demo output is labeled (letters[1:4] :, letters[-2:] :, letters[::2] :), so every printed line maps back to its originating operation.

Key statements

except IndexError as exc:
    print("letters[99]   : IndexError", exc)

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `letters`, `scores`.