Python ProgrammingPython Programming

Tricks of List Slicing in Python

Python slicing is a computationally fast way to methodically access parts of your data. The colons (:) in subscript notation make slice notation - which has the optional arguments, start, stop, step.

Various slicing tricks

items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
print(items[4:])  # From index 4 to last index
 
print(items[:4])  # From index 0 to 4 index
 
print(items[4:7])  # From index 4(included) up to index 7(excluded)
 
print(items[:-1])  # Excluded last item
 
print(items[:-2])  # Up to second last index(negative index)
 
print(items[::-1])  # From last to first in reverse order(negative step)
 
print(items[::-2])  # All odd numbers in reversed order
 
print(items[-2::-2])  # All even numbers in reversed order
 
print(items[::])  # All items 
Output
[4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]
[4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 7, 5, 3, 1]
[8, 6, 4, 2, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]