Python slice() function

The slice() method returns a portion of an iterable as an object of the slice class based on the specified range. It can be used with string, list, tuple, set, bytes, or range objects or custom class object that implements sequence methods __getitem__() and __len__() methods.

Syntax:

slice(stop)
slice(start, stop, step)

Parameters:

  1. start: (Optional) Starting index where the slicing of the iterable starts. Deault value is none.
  2. stop: Ending index where the slicing should end.
  3. step: (Optional) An integer to increment starting index. Defaults to None.

Return Value:

Returns an object of the slice class.

The following examples demonstrates the slice() method with a string value.

Example: slice() with String
mystr = 'TutorialsTeacher'
nums = [1,2,3,4,5,6,7,8,9,10]

portion1 = slice(9)
portion2 = slice(2, 8, 2)   

print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])

print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2])
Output
slice: slice(None, 9, None)
String value: Tutorials
List value: [1,2,3,4,5,6,7,8,9]

slice: slice(2, 8, 2)
String value: tra
List value: [3, 5, 7]

Above, slice(9) returns the slice object as slice(None, 9, None), which you can pass to any iterable object to get that index portion.

The slice() method can be used with string, list, tuple, set, bytes, or range. The following example fetch the portion of the list object.

Example: slice() with List, Tuple
nums = [1,2,3,4,5,6,7,8,9,10]
odd_portion = slice(0, 10, 2)
print(nums[odd_portion])

even_portion = slice(1, 10, 2)
print(nums[even_portion])
Output
[1, 3, 5, 7, 9] 
[2, 4, 6, 8, 10]

Using Negative Index

The slice() method also supports negative indexing.

Example: slice() with Negative Indexing
nums = [1,2,3,4,5,6,7,8,9,10]
even_portion = slice(-9, -1, 2)
print(nums[even_portion])
Output
[2, 4, 6, 8]

Using Indexing Syntax

You can use iterable_obj[start:stop:step] shortcut syntax for slicing instead of using the slice() method.

Example: obj[start:stop:step] Syntax
nums = [1,2,3,4,5,6,7,8,9,10]
print('Odd nums: ', nums[0:10:2]) # start 0, stop: 10, step:2
print('Even nums: ', nums[1:10:2]) # start 1, stop: 10, step:2

mystr = 'TutorialsTeacher'
print(mystr[0:9]) # start 0, stop: 9, step:1
print(mystr[9:]) # start 9, stop: end of string, step:1
print(mystr[9::2]) # start 9, stop: end of string, step:2
print(mystr[::2]) # start 0, stop: end of string, step:2
Output
Odd nums: [1, 3, 5, 7, 9] 
Even nums: [2, 4, 6, 8, 10]
Tutorials
Teacher
Tahr
Ttrasece