How to Use Slice Function in PythonPython Basics


The slice() method specifies how to slice a sequence. Through this function, you can specify where to start the slicing, and where to end.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

temp = ("1", "2", "3", "A", "B", "C", "D", "E")
x = slice(0, 8, 3)
print(temp[x])

Output:

('1', 'A', 'D')

Syntax

slice(start, end, step)

Parameters

Name Description
start An integer number specifying where to start the slicing.
end An integer number specifying where to end the slicing
step An integer number specifying the step of the slicing.

Return Value

It returns a slice object.


  • Slice() function creates a slice object.
  • A slice object is used to specify how to slice a sequence by range(start, end, step).
  • Python supports the following data types for slice operations: list, tuple, string, unicode, and range.
  • The type returned by slice operation is the same as original data type.
  • Slice operation does not change original data but regenerates a new data.

2. Parameters

  • start: indicates starting index.
  • end: indicates end index.
  • step: indicates step size. The step size cannot be 0, and the default value is 1.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

alist = ['A','B','C','D','E','F']
print(alist[1:2:6])
print(alist[:])
print(alist[0:5])
print(alist[:5])
print(alist[::1])

# Create 3 slice objects 
object = slice(1,2,6)
print(alist[object])

object = slice(0,6,1)
print(alist[object])

object = slice(6)
print(alist[object])

Output:

['B']
['A', 'B', 'C', 'D', 'E', 'F']
['A', 'B', 'C', 'D', 'E']
['A', 'B', 'C', 'D', 'E']
['A', 'B', 'C', 'D', 'E', 'F']
['B']
['B', 'C', 'D', 'E', 'F']
['A', 'B', 'C', 'D', 'E', 'F']

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us