Python slicing is used to slice lists or tuples. Let us learn Python slicing through examples.
Let us declare a Python list.
x = [1,2,3,4,5,6,7,8,9]
Python slicing can be done in two ways...
x[start:stop:step] -- Select items at every step (index) from Start through stop-1
x[slice(start,stop,step) -- Select items at every step (index) from Start through stop-1
Note step (argument) is optional
x[0:1]
[1]
x[0:1:1]
[1]
x[slice(0,1)]
[1]
x[slice(0,1,1)]
[1]
Note step parameter is optional, by default it is 1.
x[1:]
[2, 3, 4, 5, 6, 7, 8, 9]
x[:8]
[1, 2, 3, 4, 5, 6, 7, 8]
x[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The below command means start from index 0 and extract every 2nd element.
index 0 , index (2) 0 +2, index (4) 0 + 2 +2, index (6) 0 + 2 + 2 +2 , index (8) 0 + 2 + 2 + 2 +2
Note two colons in the below syntax. There is nothing between Ist and 2nd colon that means evreything from start to end of list.
x[0::2]
[1, 3, 5, 7, 9]
Negative step of -1 means go from right to left
Positive step of 1 means go from left to right
Negative number -1 means last element, -2 means seconda last element so on and so forth.
x[-1]
9
The below syntax will print nothing, because index is starting from -1 which means last element in the list then it goes to index 0 because by default step is 1 but our "stop" is -3. To fix this we will have to give step of -1.
x[-1:-3]
[]
As we can see, the index will start from -1, the last element, then goes to -2 because step is -1, then stops at -3
x[-1:-3:-1]
[9, 8]
x[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Note in the above, since step is -1, Python considers start:stop as -1:-10, we can re-write above as shown below.
x[-1:-10:-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
print last 3 elements. Note below syntax means -3 to last element (right to left) and step is 1 by default
x[-3:]
[7, 8, 9]
Below syntax means, start at -3 index, then go to (-5) -3-2 so on and so forth to all the way to start of the list (right to left) because step is -1.
x[-3::-2]
[7, 5, 3, 1]
x[1::-1]
[2, 1]
Let us see how did the above slicing syntax works.
The index will start at...
index 1, index (0) 1-1
Note -1 tells it go from right to left
x[1::-1]
[2, 1]
x[-3::-1]
[7, 6, 5, 4, 3, 2, 1]
Note all the above can be used with slice method. The different is instead of ":" (colon) use None to indicate end or start of list index.
x[slice(-3,None,-1)]
[7, 6, 5, 4, 3, 2, 1]