Python slice() Function
slice() is a built-in function in Python used to create slice objects.
A slice object specifies the range of a sequence slice and can be used anywhere slicing is supported, such as lists, tuples and strings.
Word meaning: slice means "slice" and is used to create slice objects.
Basic syntax and parameters
Syntax format
slice(stop)
slice(start, stop)
slice(start, stop, step)
Parameter Description
- Parameter start(optional):
- Type: integer
- Description: the starting position of the slice; defaults to 0.
- Parameter stop:
- Type: integer
- Description: the ending position of the slice (exclusive).
- Parameter step(optional):
- Type: integer
- Description: the step of the slice; defaults to 1.
Function description
- Return Value: Returns a slice object.
- Feature: Slice objects can be reused, which is very convenient.
Example
Example 1: creating slice objects
Example
Create a slice object
s1
=
slice
(
5
)
From 0 to 5
s2
=
slice
(
1
,
5
)
From 1 to 5
s3
=
slice
(
0
,
10
,
2
)
From 0 to 10 with step 2
Use it in a list slice
my_list
=
[
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
(
my_list
[
s1
]
)
Output: [0, 1, 2, 3, 4]
(
my_list
[
s2
]
)
Output: [1, 2, 3, 4]
(
my_list
[
s3
]
)
Output: [0, 2, 4, 6, 8]
Expected output:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[0, 2, 4, 6, 8]
Code analysis:
slice(5)is equivalent to[0:5]。slice(1, 5)is equivalent to[1:5]。slice(0, 10, 2)is equivalent to[0:10:2]。
Example 2: attributes of a slice object
Example
View the attributes of the slice object
s
=
slice
(
1
,
10
,
2
)
(
s.
start
)
Output: 1
(
s.
stop
)
Output: 10
(
s.
step
)
Output: 2
Negative indices
s
=
slice
(
3
,
1
)
(
s.
start
)
Output: -3
(
s.
stop
)
Output: -1
Expected output:
1
10
2
-3
-1
Code analysis:
- A slice object has three attributes: start, stop and step.
- Negative indices are supported.
Example 3: practical applications
Example
Create a reusable slice
first_three
=
slice
(
3
)
last_three
=
slice
(
3
,
None
)
my_list
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
(
my_list
[
first_three
]
)
Output: [1, 2, 3]
(
my_list
[
last_three
]
)
Output: [7, 8, 9]
Use it for multi-dimensional slicing
matrix
=
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
row
=
slice
(
0
,
2
)
The first two rows
col
=
slice
(
1
,
3
)
Columns 2-3
(
[
row
[
col
]
for
row
in
matrix
[
row
]
]
)
Output: [[2, 3], [5, 6]]
Expected output:
[1, 2, 3]
[7, 8, 9]
[[2, 3], [5, 6]]
The main advantage of slice objects is that they can be reused, making the code clearer.
Python3 built-in function