In Python, Slicing is a powerful technique used to extract a specific portion (a "slice") of a sequence, such as a string, list, or tuple. While indexing retrieves a single item, slicing allows you to retrieve a range of items.
The basic syntax for slicing is:
sequence[start : stop : step]
start: The index where the slice begins (included). If omitted, it defaults to 0.
stop: The index where the slice ends (excluded). The slice goes up to, but does not include, this index. If omitted, it defaults to the end of the sequence.
step: Determines the increment between each index for the slice. If omitted, it defaults to 1.
Non-Destructive: Slicing does not modify the original sequence; it creates a new one.
Out-of-Bounds Handling: Unlike indexing (which throws an error if the index is too high), slicing is "forgiving." If the stop index is greater than the sequence length, Python simply stops at the end.
Negative Slicing: You can use negative numbers to slice from the end of the sequence.
Extracting a substring by defining the boundaries.
text = "Python Programming" # Extract 'Python' (Indices 0 to 5) print(text[0:6]) # Extract 'Programming' (From index 7 to the end) print(text[7:]) # Extract from the beginning to index 6 print(text[:6])
The step allows you to skip characters or change the direction of the slice.
numbers = "0123456789" # Every second character (Even numbers) print(numbers[::2]) # Output: "02468" # Every third character starting from index 1 print(numbers[1::3]) # Output: "147"
Negative indices allow you to count backward from the end (-1 is the last character).
phrase = "Hello World" # Get the last 5 characters print(phrase[-5:]) # Output: "World" # Reverse the entire string (Very common Python trick) reversed_phrase = phrase[::-1] print(reversed_phrase) # Output: "dlroW olleH"
If we have the string "PYTHON":
| P | Y | T | H | O | N |
| 0 | 1 | 2 | 3 | 4 | 5 |
| -6 | -5 | -4 | -3 | -2 | -1 |
"PYTHON"[1:4] results in YTH.
"PYTHON"[-4:-1] results in THO.
| Operation | Syntax | Result for "ABCDE" |
| Full Copy | [:] | "ABCDE" |
| From Start | [:3] | "ABC" |
| To End | [2:] | "CDE" |
| Step Skip | [::2] | "ACE" |
| Reverse | [::-1] | "EDCBA" |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION