> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python slice

A slice in Python is a programmatic mechanism used to extract a specific range of elements from a sequence (such as lists, tuples, or strings) or any custom object implementing the `__getitem__()` magic method. It operates by generating a `slice` object that defines the indices to be accessed based on a defined start, stop, and stride.

## Syntax

Slicing can be invoked using the extended indexing syntax (bracket notation) or by explicitly instantiating a `slice` object.

```python theme={"dark"}
sequence = [10, 20, 30, 40, 50]


# Extended indexing syntax
print(sequence[1:4:2])  # Output: [20, 40]


# Explicit slice object instantiation
slice_obj = slice(1, 4, 2)
print(sequence[slice_obj])  # Output: [20, 40]
```

## Parameter Mechanics

The slice operation is governed by three parameters. When omitted in the bracket notation, the actual default value for each parameter is `None`. The Python interpreter resolves `None` to specific effective bounds based on the sequence length and the `step` direction.

* **`start` (Inclusive):** The zero-based index where the extraction begins.
  * *Effective Resolution (if `None`):* `0` if `step` is positive; `len(sequence) - 1` (the last element) if `step` is negative.
* **`stop` (Exclusive):** The zero-based index where the extraction halts. The element at this index is not included in the result.
  * *Effective Resolution (if `None`):* `len(sequence)` if `step` is positive; effectively `-1` if `step` is negative (ensuring index `0` is included).
* **`step` (Stride):** The integer interval between consecutive indices.
  * *Effective Resolution (if `None`):* `1`.
  * *Constraint:* Must not be `0` (raises a `ValueError`). A negative `step` reverses the traversal direction.

## Index Resolution and Bounds Handling

Python applies specific resolution rules to slice indices before extraction:

1. **Negative Indexing:** If a provided `start` or `stop` is negative, Python resolves it relative to the sequence length by adding the length of the sequence to the index (`resolved_index = len(sequence) + index`).
2. **Bounds Clamping:** Unlike single-element indexing, slicing does not raise an `IndexError` for out-of-bounds indices. Instead, Python clamps the values to the sequence's actual limits based on the `step` direction:
   * *Positive `step`:* Out-of-bounds indices are clamped to the boundaries of `[0, len(sequence)]`. Any index less than `0` is clamped to `0`, and any index greater than `len(sequence)` is clamped to `len(sequence)`.
   * *Negative `step`:* Out-of-bounds indices are clamped to the boundaries of `[-1, len(sequence) - 1]`. Any index less than `-1` is clamped to `-1`, and any index greater than `len(sequence) - 1` is clamped to `len(sequence) - 1`.

## Internal Implementation

When the Python interpreter encounters the `[start:stop:step]` syntax, it translates this into a `slice` object. This object is then passed as the `key` argument to the sequence's `__getitem__(self, key)` method.

```python theme={"dark"}
class CustomSequence:
    def __getitem__(self, key):
        if isinstance(key, slice):
            # The key is a slice object with .start, .stop, and .step attributes
            return f"Start: {key.start}, Stop: {key.stop}, Step: {key.step}"

obj = CustomSequence()
print(obj[1:10:2])  # Output: Start: 1, Stop: 10, Step: 2
```

For mutable sequences, slices can also be passed to `__setitem__(self, key, value)` for slice assignment, or `__delitem__(self, key)` for slice deletion.

## Memory and Object Behavior

* **Shallow Copying and Memory Optimization:** For mutable built-in sequences (like lists), a slice operation allocates a new object and creates a shallow copy of the sequence (populating it with references to the elements in the specified range). However, for immutable sequences (like strings, tuples, and `bytes`), a full slice (e.g., `sequence[:]`) returns a reference to the exact same original object as a memory optimization, rather than allocating a new one. Standard Python slicing does not create a memory view of the original sequence (unlike slicing in libraries such as NumPy).
* **Slice Assignment:** When assigning an iterable to a slice of a mutable sequence (`sequence[start:stop:step] = iterable`), Python replaces the targeted slice with the elements of the iterable. The behavior depends on the `step` value:
  * *Standard Slices (`step` is `1` or omitted):* If the length of the iterable differs from the length of the slice, the underlying sequence is dynamically resized to accommodate the new elements.
  * *Extended Slices (`step != 1`):* The sequence cannot be dynamically resized. The length of the assigned iterable must exactly match the number of elements in the slice; attempting to assign an iterable of a different length raises a `ValueError`.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
