The format for list slicing is [start:stop:step].
- start is the index of the list where slicing starts.
- stop is the index of the list where slicing ends.
- step allows you to select nth item within the range start to stop.
List slicing works similar to Python slice() function.
Get all the Items
my_list = [1, 2, 3, 4, 5]
print(my_list[:])
Output
[1, 2, 3, 4, 5]
Get all the Items After a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
Output
[3, 4, 5]
Please note that indexing starts from 0. Item on index 2 is also included.
Get all the Items Before a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])
Output
[1, 2]
The items before index 2 are sliced. Item on index 2 is excluded.
Get all the Items from One Position to Another Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Output
[3, 4]
The starting position (i.e. 2) is included and the ending position (i.e. 4) is excluded.
Get the Items at Specified Intervals
my_list = [1, 2, 3, 4, 5]
print(my_list[::2])
Output
[1, 3, 5]
The items at interval 2 starting from index 0 are sliced.
If you want the indexing to start from the last item, you can use negative sign -.
my_list = [1, 2, 3, 4, 5]
print(my_list[::-2])
Output
[5, 3, 1]
The items at interval 2 starting from the last index are sliced.
If you want the items from one position to another, you can mention them from start
to stop
.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4:2])
Output
[2, 4]
The items from index 1 to 4 are sliced with intervals of 2.