Python - List Slicing
In Python, slicing of a list is done to extract part of the list. To perform a slicing operation on a list, there are two methods which are mentioned below:
- using python slice function
- using index syntax for slicing
Using python slice function
The Python slice() function has one required parameter which is used to specify stop location of slicing. Additionally, it has two optional parameters to specify start location of slicing and step size of slicing.
slice(start, stop, size) iterable[slice(start, stop, size)]
start |
Optional. specify the location to start slicing. default is start of the iterable. |
stop |
Required. specify the location to stop slicing. |
size |
Optional. specify the step size of slicing. |
In the example below, the slice() function is used on a list called MyList to slice it in different way. Python supports negative indexing as well which can also be used to slice the list.
MyList = [0, 1, 2, 3, 4, 5, 6, 7, 9 ,10] # specifying stop location iter_1 = slice(4) print(MyList[iter_1]) iter_2 = slice(-4) print(MyList[iter_2]) print() # specifying start and stop location iter_3 = slice(1,4) print(MyList[iter_3]) iter_4 = slice(-4,-1) print(MyList[iter_4]) print() # specifying start, stop and step size iter_5 = slice(1,8,2) print(MyList[iter_5]) iter_6 = slice(-8,-1,2) print(MyList[iter_6])
The output of the above code will be:
[0, 1, 2, 3] [0, 1, 2, 3, 4, 5] [1, 2, 3] [6, 7, 9] [1, 3, 5, 7] [2, 4, 6, 9]
Using index syntax for slicing
Similarly, the index syntax can be used to slice a list. The syntax for using this method is given below:
list[start:stop:size]
In the example below, the index syntax is used to slice a list called MyList. The negative indexing can be used here also.
MyList = [0, 1, 2, 3, 4, 5, 6, 7, 9 ,10] # specifying stop location print(MyList[:4]) print(MyList[:-4]) print() # specifying start location print(MyList[2:]) print(MyList[-4:]) print() # specifying start and stop location print(MyList[1:4]) print(MyList[-4:-1]) print() # specifying start, stop and step size print(MyList[1:8:2]) print(MyList[-8:-1:2])
The output of the above code will be:
[0, 1, 2, 3] [0, 1, 2, 3, 4, 5] [2, 3, 4, 5, 6, 7, 9, 10] [6, 7, 9, 10] [1, 2, 3] [6, 7, 9] [1, 3, 5, 7] [2, 4, 6, 9]
❮ Python - Lists