Python slice() function returns a sliced object from the set of indexes of the input specified by the user in accordance with the arguments passed to it.
Thus, it enables the user to slice any sequence such as Lists, Tuples, Strings, etc.
Syntax:
slice(Stop)
slice(Start, Stop[, Step)
- Start: (Optional) An integer that specifies the index to initiate the slicing process.
- Stop: An integer that specifies the end index to the slice() method.
- Step: (Optional) An integer that specifies the step of the slicing process.
Value returned by the slice() function:
A sliced object.
Basic Understanding of slice() function
Example:
print("Printing arguments passed to the slice().... ")
input = slice(4)
print(input.start)
print(input.stop)
print(input.step)
input = slice(1,4,6)
print(input.start)
print(input.stop)
print(input.step)
Output:
Printing arguments passed to the slice()....
None
4
None
1
4
6
Python slice() with Strings
Python slice() function can be used along with Strings in two different ways:
- slice() function with positive indexes
- slice() function with negative indexes
1. slice() function with positive indexes
Example:
input='Engineering'
result=input[slice(1,6)]
print(result)
Output:
ngine
2. slice() function with negative indexes
Example:
input='Engineering'
result=input[slice(-5,-1)]
print(result)
Output:
erin
Python slice() with Lists
Example:
input_list = slice(1, 5)
my_list = ['Safa', 'Aman', 'Raghav', 'Raman', 'JournalDev', 'Seema']
print(my_list[input_list])
Output:
['Aman', 'Raghav', 'Raman', 'JournalDev']
Python slice() with Tuples
Example:
input_tuple = slice(1, 5)
my_tuple = ['Safa', 'Aman', 'Raghav', 'Raman', 'JournalDev', 'Seema']
print(my_tuple[input_tuple])
Output:
['Aman', 'Raghav', 'Raman', 'JournalDev']
Extended indexing with Python slice()
A shorthand method can be used to serve the functionality of Python slice().
Syntax:
input[start:stop:step]
Example:
my_tuple = ['Safa', 'Aman', 'Raghav', 'Raman', 'JournalDev', 'Seema']
result = my_tuple[1:3]
print(result)
Output:
['Aman', 'Raghav']
Deletion of Python Slices
The del keyword can be used to delete the applied Slicing on a particular input element.
Example:
my_tuple = ['Safa', 'Aman', 'Raghav', 'Raman', 'JournalDev', 'Seema']
del my_tuple[:2]
print(my_tuple)
Output:
['Raghav', 'Raman', 'JournalDev', 'Seema']
Conclusion
Thus, in this article, we have understood the basic functionality of Python slice() function.
References
- Python slice() documentation
- Python slice() function