slice() is Python’s built-in function for creating slice objects — the same kind used in seq[start:stop:step] slicing syntax, but as a reusable, first-class object. This allows dynamic slicing, passing slices as arguments, storing them, and applying them to multiple sequences without hardcoding indices. In 2026, slice() remains a powerful tool in data science (dynamic windowing in pandas/Polars/Dask time series), software engineering (configurable slicing in APIs, batch processing), and performance-critical code — enabling efficient, memory-safe strided access, chunking, and reverse iteration on large arrays and streams.
Here’s a complete, practical guide to using slice() in Python: basic creation & application, slicing with objects, real-world patterns (earthquake time series windowing, strided feature extraction, batch processing), and modern best practices with type hints, performance, negative indices, and integration with NumPy/Dask/Polars/pandas/xarray.
Basic slice(start, stop, step) — create slice object, apply via indexing.
# Simple slice object
s = slice(2, 8, 2) # start=2, stop=8, step=2
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[s]) # [2, 4, 6]
text = "Hello, World!"
print(text[s]) # "llo,"
# Negative step (reverse)
rev = slice(None, None, -1)
print(text[rev]) # "!dlroW ,olleH"
# From end: slice(-5, None) ? last 5 items
print(nums[slice(-5, None)]) # [5, 6, 7, 8, 9]
Real-world pattern: dynamic time series windowing in earthquake data — reusable slice objects.
import pandas as pd
df = pd.read_csv('earthquakes.csv', parse_dates=['time'])
df = df.sort_values('time').reset_index(drop=True)
# Define reusable slices
last_100 = slice(-100, None) # last 100 events
every_10th = slice(None, None, 10) # every 10th event
recent_strong = slice(-500, -100, -1) # last 400 strong events backward
# Apply slices
recent_events = df.iloc[last_100]
print(f"Last 100 events: {len(recent_events)} rows")
sampled = df.iloc[every_10th]
print(f"Every 10th event: {len(sampled)} rows")
# Reverse recent strong (newest first)
strong_recent = df[df['mag'] >= 7.0].iloc[recent_strong]
print(strong_recent[['time', 'mag', 'place']].head())
# Polars: slice in lazy mode
import polars as pl
pl_df = pl.from_pandas(df)
last_50 = pl_df.slice(-50, None) # Polars native slice
print(last_50)
Best practices for slice() in Python & data workflows. Prefer slice objects — when slices are reused or dynamic: window = slice(start, stop, step); df.iloc[window]. Modern tip: use Polars df.slice(offset, length) — for lazy slicing; Dask ddf.iloc[start:stop:step]. Use slice(None) — for full axis: arr[slice(None), 0]. Use negative indices — slice(-10, None) for last 10. Add type hints — from typing import Sequence; def apply_window(seq: Sequence, sl: slice) -> Sequence. Use slice() with numpy.s_ — arr[np.s_[::2]] (same as arr[::2]). Use slice() in functions — pass as argument for configurable slicing. Use slice(start, stop) — omit step when 1. Use slice(None, None, -1) — full reverse. Use slice(None, n) — first n items. Use slice(-n, None) — last n items. Use slice(0, None, 2) — every other item. Use slice() with itertools.islice() — islice(iterable, sl.start, sl.stop, sl.step). Use slice() in custom classes — override __getitem__ to accept slice. Use slice.indices(len(seq)) — get (start, stop, step) clamped to sequence length. Use slice.indices() — for safe slicing on unknown lengths. Use slice() in pandas — df.iloc[slice(0, 100)]. Use slice() in NumPy — arr[slice(0, 1000, 10)]. Use slice() in Dask — ddf.iloc[slice(0, 100000)]. Use slice() in xarray — ds.isel(time=slice(0, 100)).
slice(start, stop, step) creates reusable slice objects — apply via indexing, pass to functions, use negative steps, and integrate with pandas/Polars/Dask/NumPy for dynamic windowing and strided access. Master slice(), and you’ll write clean, configurable, memory-efficient slicing code in any Python workflow.
Next time you need a reusable slice — use slice(). It’s Python’s cleanest way to say: “Define a range of indices — then apply it anywhere, anytime.”