Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python slice() Function

Python slice() Function

Python3 Built-in Functions Python3 built-in 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

- Type: integer - Description: the starting position of the slice; defaults to 0. - Type: integer - Description: the ending position of the slice (exclusive). - Type: integer - Description: the step of the slice; defaults to 1.

Function description


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

]

print

(

my_list

[

s1

]

)

 

Output: [0, 1, 2, 3, 4]

print

(

my_list

[

s2

]

)

 

Output: [1, 2, 3, 4]

print

(

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:

  1. slice(5) is equivalent to [0:5]。
  2. slice(1, 5) is equivalent to [1:5]。
  3. 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

)

print

(

s.

start

)

 

Output: 1

print

(

s.

stop

)

   

Output: 10

print

(

s.

step

)

   

Output: 2

Negative indices

s

=

slice

(

3

,

1

)

print

(

s.

start

)

 

Output: -3

print

(

s.

stop

)

   

Output: -1

Expected output:

1
10
2
-3
-1

Code analysis:

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

]

print

(

my_list

[

first_three

]

)

 

Output: [1, 2, 3]

print

(

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

print

(

[

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 Functions Python3 built-in function