25
Python slice()
ItsMyCode |
The slice()
in Python is a built-in function that returns a slice object and slices any sequence such as string , tuple , list , bytes, range.
The syntax of the slice()
is:
**slice(start, stop, step)**
The slice()
method can take three parameters.
-
start (optional) – Starting integer where the slicing of the object starts. If omitted, defaults to
None
. - stop – Ending index where the slicing of object stops. The slicing stops at index stop -1 (last element).
-
step (optional) – An optional argument determines the increment between each index for slicing. If omitted, defaults to
None
.
Note: If only one parameter is passed, then both start and step will default to None
.
The slice()
method returns a sliced object containing elements in the given range.
Note : We can use slice with any object which supports sequence protocol which means an object that implements __getitem__ ()
and __len()__
method.
# Python program to demonstrate slice() operator
# String slicing
str = 'ItsMyPythonCode'
s1 = slice(3)
s2 = slice(5, 11,1)
print(str[s1])
print(str[s2])
Output
Its
Python
In Python, negative sequence indexes represent positions from the end of the array. The slice()
function can take negative values, and in the case of a negative index, the iteration starts from end
to start
.
# Python program to demonstrate slice() operator
# String slicing
str = 'ItsMyPythonCode'
s1 = slice(-4)
s2 = slice(-5, -11,-1)
print(str[s1])
print(str[s2])
Output
ItsMyPython
nohtyP
# Python program to demonstrate slice() operator
# List slicing
lst = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print(lst[s1])
print(lst[s2])
# Negative list slicing
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print(lst[s1])
print(lst[s2])
Output
[1, 2, 3]
[2, 4]
[1, 2]
[5, 3]
# Python program to demonstrate slice() operator
# Tuple slicing
tup = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print(tup[s1])
print(tup[s2])
# Negative Tuple slicing
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print(tup[s1])
print(tup[s2])
Output
(1, 2, 3)
(2, 4)
(1, 2)
(5, 3)
The post Python slice() appeared first on ItsMyCode.
25