Python slice() function

In this article, we will learn about the Python slice() function/method with the help of multiple examples.Example

Python3

String = 'Hello World'
slice_obj = slice(5,11)
print(String[slice_obj])


Output: 

 World

A sequence of objects of any type (string, bytes, tuple, list, or range) or the object which implements __getitem__() and __len__() functions/method then this object can be sliced using slice() method.

Python slice() Function Syntax

Syntax: slice(start, stop, step)

Parameters:

  • start: Starting index where the slicing of object starts.
  • stop: Ending index where the slicing of object stops.
  • step: It is an optional argument that determines the increment between each index for slicing.

Return Type: Returns a sliced object containing elements in the given range only.

Note: If just one parameter is passed, then the start and step are considered to be None.

slice() Function in Python Examples

Python slice string

We have created the string CodeConfig, and we are using the slice function/method to slice the string. The first slice function/method is slicing the string to the 2nd index, the second slice function/method is have used to slice the string to the 4th index with a leaving 2nd index. Finally, we are printing both sliced strings in the terminal.

Python3

# String slicing
String = 'CodeConfig'
slice_obj1 = slice(3)
slice_obj2 = slice(1, 5, 2)
print("String slicing")
print(String[slice_obj1])
print(String[slice_obj2])


Output:

String slicing
Cod
eC

Python slice list or Python slice array

We have created the list [1,2,3,4,5], and we are using the slice function/method to slice the list. The first slice function/method is slicing the list to the 2nd index, the second slice function/method is have used to slice the list to the 4th index with a leaving 2nd index. Finally, we are printing both sliced lists in the terminal.

Python3

L = [1, 2, 3, 4, 5]
slice_obj1 = slice(3)
slice_obj2 = slice(1, 5, 2)
print("List slicing")
print(L[slice_obj1])
print(L[slice_obj2])


Output:

List slicing
[1, 2, 3]
[2, 4]

Python slice tuple

We have created a tuple of 5 numbers, and we are using the slice function/method 2 times, first slice function/method is slicing the tuple to 2 indexes, and the second slice function/method is slicing the tuple to 4 indexes and every second element is sliced.

Python3

# Tuple slicing
T = (1, 2, 3, 4, 5)
slice_obj1 = slice(3)
slice_obj2 = slice(1, 5, 2)
print("Tuple slicing")
print(T[slice_obj1])
print(T[slice_obj2])


Output:

Tuple slicing
(1, 2, 3)
(2, 4)

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array. slice() function/method can also have negative values. In that case, the iteration will be performed backwards i.e. from end to start.

Get a sub-list using a negative index with a slice()

In the example. We have created a list with values ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’. We are slicing the string from the 2nd index from the last and going to the 6th index from the last, with the hop of -1.

Python3

l = ['a', 'b', 'c', 'd', 'e', 'f']
slice_obj = slice(-2, -6, -1)
print("list slicing:", l[slice_obj])


Output:

list slicing: ['e', 'd', 'c', 'b']

Get a sub-string using a negative index with a slice()

We have created a string of letters, we are using the slice function/method with a negative index of -1 to slice the string apart from the last letter.

Python3

s = "Codes"
slice_obj = slice(-1)
print("string slicing:", s[slice_obj])


Output:

string slicing: Code

Get a sub-tuple using a negative index with slice()

In the code, slice_obj = slice(-1, -3, -1) creates a slice object that will slice the tuple starting from the second-to-last element (index -1), up to (but not including) the fourth-to-last element (index -3), with a step size of -1. This means that the sliced tuple will contain the elements [9, 7], in reverse order.

Python3

t = (1, 3, 5, 7, 9)
slice_obj = slice(-1, -3, -1)
print("tuple slicing:", t[slice_obj])


Output:

tuple slicing: (9, 7)

Using Indexing Syntax for Slicing with String

In the example, we have created a list named slice_str with the value ‘CodesForCodes‘.The first slice is printing the value till the 4 indexes and the second slice is printing till the 5th index with a hop of every 2nd index.

Python3

slice_str = 'CodesForCodes'
print(slice_str[0:5]) 
print(slice_str[1:6:2])


Output:

Codes
esF

Using Indexing Syntax for Slicing with List

In the example, we have created a list named slice_list and we have inserted [‘C’,’o’,’d’,’e’,’s’,’F’,’o’,’r’,’C’,’o’,’d’,’e’,’s’] these values to our list. The first slice is printing the value till 4 indexes and the second slice is printing till the 5th index with a hop of every 2nd index.

Python3

slice_list = ['C','o','d','e','s','F','o','r','C','o','d','e','s']
print(slice_list[0:5]) 
print(slice_list[1:6:2])


Output:

['C', 'o', 'd', 'e', 's']
['e', 's', 'F']

Slicing and modifying a list

In the example, we have created a list of numbers named slice_numbers which consists of 5 variables [1,2,3,4,5] in it.Then we are slicing the list from index 1 to 3 and also modify its value from [1,2,3] to [10,20,30] and finally, we are printing the slice_numbers list.

Python3

slice_numbers = [1, 2, 3, 4, 5]
print("slice_number before slicing and modfication : ",end=' ')
print(slice_numbers)
slice_numbers[1:4] = [10, 20, 30]
print("slice_number after slicing and modfication : ",end=' ')
print(slice_numbers)


Output:

slice_number before slicing and modfication :  [1, 2, 3, 4, 5]
slice_number after slicing and modfication :  [1, 10, 20, 30, 5]

Explore More

Explain about Hugging Face Transformers

Hugging Face Transformers is a powerful library designed for natural language processing (NLP), computer vision, and audio tasks. It provides state-of-the-art pretrained models and tools for fine-tuning and deploying these

AI Roadmap using Python

Python is a great foundation for diving into AI! To take the next step in your AI learning journey, here’s a roadmap to guide you. 1. Strengthen Your Math Skills

Create new Python Virtual environment

Create a new virtual environment  Python 3 allows you to manage separate package installations for different projects. It creates a “virtual” isolated Python installation. When you switch projects, you can