











slice() Function in Python programming language


slice() Function
Slice() Function in Python programming language is a built-in function used to iterate through the sequences. Slice function takes three arguments 1st is starting point 2nd is ending point and 3rd for the order to print the element. Sequence data-type is list, tuple, the string is the data-type where we can perform slice operation using slice function.


slice() function for different data-types
slice() function for list
The list is a sequential data-type and is mutable. we can perform operations on the list using the slice built-in function. Slice function in the list takes 3 arguments where one of them is a mandatory field and two are optional. Let’s have a look at some operations on the list using builtin- slice(0 functions.


Python code for slice function on list
arr = ['P','r','e','p','I','n','s','t','a'] #Slicing in list with 2 arguments a = slice(1,4) print(arr[a]) #slicing in list with 1 argument a = slice(2) print(arr[a]) a = slice(-1) print(arr[a]) #Slicing in list with 3 arguments a = slice(1,5,1) print(arr[a])
Output: ['r', 'e', 'p'] ['P', 'r'] ['P', 'r', 'e', 'p', 'I', 'n', 's', 't'] ['r', 'e', 'p', 'I']


slice() function for Tuple
A tuple is same as list data-type. But the major difference between list and tuple is that tuple is an immutable data-type. Although we can perform some operations on the tuple. Since built-in function takes the arguments and represents the tuple from a starting point to endpoint.
Python code for slice() function on tuple
arr = tuple(['P','r','e','p','I','n','s','t','a']) #Slicing in list with 2 arguments a = slice(1,4) print(arr[a]) #slicing in list with 1 argument a = slice(2) print(arr[a]) a = slice(-1) print(arr[a]) #Slicing in list with 3 arguments a = slice(1,5,1) print(arr[a])
Output: ['r', 'e', 'p'] ['P', 'r'] ['P', 'r', 'e', 'p', 'I', 'n', 's', 't'] ['r', 'e', 'p', 'I']
slice() in Strings
String data-type is an immutable data-type in python. But we can perform many operations on strings than on tuples. Strings are iterable and so we can use built-in function Slice() to print of use the sub-part of string according to our need. Lets have a look at some representations of string using slice function.


Python code for slice() function on String
arr = 'PrepInsta' #Slicing in string with 2 arguments a = slice(1,4) print(arr[a]) #slicing in string with 1 argument a = slice(2) print(arr[a]) a = slice(-1) print(arr[a]) #Slicing in string with 3 arguments a = slice(1,5,1) print(arr[a])
Output: rep Pr PrepInst repI
Login/Signup to comment