![]() |
VOOZH | about |
In Python, slicing allows us to extract parts of sequences like strings, lists and tuples. While normal slicing uses positive indices, Python also supports negative slicing, which makes it easier to work with elements starting from the end of a sequence.
Python uses negative indices to count elements from the end.
This feature is especially useful when you donβt know exact length of a sequence but still want to access elements from the end.
Example: Here we access elements from the end of a string using negative indices.
n h
Explanation:
In Python, negative slicing can be done in two ways:
Both methods allow us to specify the start, end and step positions using negative indices.
This is the most common way to perform slicing. The colon (:) operator accepts three optional parameters:
Syntax:
sequence[start : end : step]
Parameters:
Example: Here we slice a string into left, middle and right parts using negative indices.
Geeks for Geeks
Explanation:
Python also provides the slice() function to achieve the same result in a more explicit way.
Syntax:
slice(start, stop, step)
Parameters:
Example: Here we use the slice() function to achieve the same slicing as before.
Geeks for Geeks
Explanation:
Negative slicing allows us to work with elements from the end of sequences like lists and tuples. Below are some useful examples.
Example: In this code, we create a list called items. Using negative slicing, we extract last four elements as vegetables and two elements before them as fruits.
['ginger', 'Potato', 'carrot', 'Chilli'] ['apple', 'guava']
Example: Here, we reverse entire list by passing -1 as the step value. The first method uses normal slicing and second uses slice() function with None for start and end and -1 as step.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Example: In this example, we extract alternate elements from the list in reverse order. By passing -2 as the step, we skip one element while moving backwards.
[10, 8, 6, 4, 2] [10, 8, 6, 4, 2]
Example: This code demonstrates negative slicing with tuples. We access last three elements, select a middle range, reverse the tuple and also extract alternate elements in reverse.
(7, 8, 9) (5, 6, 7) (9, 8, 7, 6, 5, 4, 3, 2, 1) (9, 7, 5, 3, 1)