The Wayback Machine - https://web.archive.org/web/20240906195010/https://www.geeksforgeeks.org/python-slice-function/
Open In App

Python slice() function

Last Updated : 09 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn about the Python slice() function 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__() 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 only 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 GeeksforGeeks, and we are using the slice function to slice the string. The first slice function is slicing the string to the 2nd index, the second slice function is 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 = 'GeeksforGeeks'
slice_obj1 = slice(3)
slice_obj2 = slice(1, 5, 2)
 
print("String slicing")
print(String[slice_obj1])
print(String[slice_obj2])


Output:

String slicing
Gee
ek

Python slice list or Python slice array

We have created the list [1,2,3,4,5], and we are using the slice function to slice the list. The first slice function is slicing the list to the 2nd index, the second slice function is 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 2 times, first slice function is slicing the tuple to 2 indexes, and the second slice function 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 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 with a negative index of -1 to slice the string apart from the last letter.

Python3




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


Output: 

string slicing: geek

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 ‘GeeksForGeeks‘.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 = 'GeeksForGeeks'
print(slice_str[0:5]) 
print(slice_str[1:6:2])


Output:

Geeks
ekF

Using Indexing Syntax for Slicing with List

In the example, we have created a list named slice_list and we have inserted [‘G’,’e’,’e’,’k’,’s’,’F’,’o’,’r’,’G’,’e’,’e’,’k’,’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 = ['G','e','e','k','s','F','o','r','G','e','e','k','s']
print(slice_list[0:5]) 
print(slice_list[1:6:2])


Output:

['G', 'e', 'e', 'k', 's']
['e', 'k', '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]


Previous Article
Next Article

Similar Reads

Python | Pandas Series.str.slice()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python's basi
3 min read
How To Index and Slice Strings in Python?
The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. As the string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing. Indexing Indexing means referring to an element of
3 min read
TypeError: unhashable type slice in Python
typeError is a common issue in Python that can arise due to various reasons. One specific TypeError that developers might encounter is the "Unhashable Type: 'Slice'". This error occurs when you try to use a slice object (created using the colon : notation) as a key in a dictionary or as an element in a set, which is not allowed because slices are m
5 min read
How to Slice a 3D Tensor in Pytorch?
In this article, we will discuss how to Slice a 3D Tensor in Pytorch. Let's create a 3D Tensor for demonstration. We can create a vector by using torch.tensor() function Syntax: torch.tensor([value1,value2,.value n]) Code: C/C++ Code # import torch module import torch # create an 3 D tensor with 8 elements each a = torch.tensor([[[1, 2, 3, 4, 5, 6,
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a U
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Prefix sum array in Python using accumulate function
We are given an array, find prefix sums of given array. Examples: Input : arr = [1, 2, 3] Output : sum = [1, 3, 6] Input : arr = [4, 6, 12] Output : sum = [4, 10, 22] A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, ...} are a, a+b, a+b+c and so on. We can solve this problem
1 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni
3 min read
Python | Permutation of a given string using inbuilt function
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA We have existing solution for this problem please refer Permutations of a given
2 min read
sciPy stats.tsem() function | Python
scipy.stats.tsem(array, limits=None, inclusive=(True, True)) calculates the trimmed standard error of the mean of array elements along the specified axis of the array. Its formula :- Parameters : array: Input array or object having the elements to calculate the trimmed standard error of the mean. axis: Axis along which the trimmed standard error of
2 min read
Practice Tags :