Slice Assignment Resizes Lists In Place
Slice assignment replaces, inserts, or deletes ranges in place; the assigned sequence can have any length, so the list resizes around it.
Code
# Slice assignment replaces, inserts, or deletes ranges in place;
# the assigned sequence may have any length, so the list resizes
items = ['alpha', 'beta', 'gamma', 'delta']
# Replace two items with three: the list grows by one
items[1:3] = ['beta2', 'beta3', 'gamma2']
print(items)
# An empty slice inserts without removing anything
items[0:0] = ['head']
print(items)
# Assigning nothing to a range deletes it
items[2:4] = []
print(items)
# del with a slice drops everything from the index to the end
del items[2:]
print(items)Output
Captured from a sandboxed run of this snippet in the build pipeline.
['alpha', 'beta2', 'beta3', 'gamma2', 'delta']
['head', 'alpha', 'beta2', 'beta3', 'gamma2', 'delta']
['head', 'alpha', 'gamma2', 'delta']
['head', 'alpha']How it works
Top-level bindings items hold the demo state — nothing sits inside a function scope.
What to watch out for in this file
- Every call resolves to a built-in API — no package manager ever runs.
Interactive Tools for This Topic
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `items`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.