ExampleEdit & Run
#Use the slice function

s = slice(1, 5)
L = [i for i in range(10)]
print(L[s])
Output:
[1, 2, 3, 4][Finished in 0.010851606959477067s]

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:

ExampleEdit & Run
L = [0, 2, 4, 6, 8, 10]
x = L[0:3]
print(x)
Output:
[0, 2, 4][Finished in 0.010841920971870422s]

In the above case, the slice object is created automatically when we pass the colon-separated 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.

ExampleEdit & Run
L = [0, 2, 4, 6, 8, 10]
s = slice(0, 3)
x = L[s]
print(x)
Output:
[0, 2, 4][Finished in 0.010202778968960047s]

The slice function has the following syntax 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.

Parameters:

The function returns a slice object based on the given arguments.

ExampleEdit & Run
lst = [10,20,30,40,50]
lst_slice1 = slice(2, 5)
lst_slice2 = slice(0, 3)
print(lst[lst_slice1])
print(lst[lst_slice2])
Output:
[30, 40, 50][10, 20, 30][Finished in 0.01023294311016798s]

Let us see some more  examples:

ExampleEdit & Run
T = ('Python', 'CSS', 'PHP', 'Ruby', 'Javascript', 'C++', 'Java')
print( T[slice(1, -1)] )
print( T[slice(2, -2)] )

R = range(10) 
print( list(R[slice(5)]) )
print( list(R[slice(3, 7)]) )
print( list(R[slice(0,len(R), 2)]) )
Output:
('CSS', 'PHP', 'Ruby', 'Javascript', 'C++')('PHP', 'Ruby', 'Javascript')[0, 1, 2, 3, 4][3, 4, 5, 6][0, 2, 4, 6, 8][Finished in 0.010079632047563791s]