#Use the slice function
s = slice(1, 5)
L = [i for i in range(10)]
print(L[s])
The slice()
function in Python is used to create a slice object that represents the set of indices specified by range(start, stop, step). The slice object can then be passed to a sequence to extract a part of the sequence.
Consider the following example:
L = [0, 2, 4, 6, 8, 10]
x = L[0:3]
print(x)
In the above case, the slice object is created automatically when we pass the colon-seperated range values to L in the square brackets. We can alternatively create a slice object then pass the object instead of the values themselves as shown below.
L = [0, 2, 4, 6, 8, 10]
s = slice(0, 3)
x = L[s]
print(x)
The slice function has the following syntax Syntax:
slice( stop, start = 0, step = 1)
stop | Specifies the position at which position to end the slicing. This argument is required. |
start | Specifies the position at which to start the slicing. It is optional and it defaults to 0. |
step | specifies the step of the slicing. It is also optional and defaults to 1. |
Note: All the three arguments, stop, start and step must be strictly integers.
The function returns a slice object based on the given arguments.
lst = [10,20,30,40,50]
lst_slice1 = slice(2, 5)
lst_slice2 = slice(0, 3)
print(lst[lst_slice1])
print(lst[lst_slice2])
more examples:
T = ('Python', 'CSS', 'PHP', 'Ruby', 'Javascript', 'C++', 'Java')
T[slice(1, -1)]
//('CSS', 'PHP', 'Ruby', 'Javascript', 'C++')
T[slice(2, -2)]
//('PHP', 'Ruby', 'Javascript')
R = range(10)
list(R[slice(5)])
//[0, 1, 2, 3, 4]
list(R[slice(3, 7)])
//[3, 4, 5, 6]
list(R[slice(0,len(R), 2)])
//[0, 2, 4, 6, 8]