How to Use Slice Function in Python


  • 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']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments