Methods and Functions

Python Slice()

A string, tuple, list, or an array contains multiple records of data that are of a similar data type or different data type depending on the data structure used. There might arise an issue where the programmer or the user might want to extract or access a certain part of data stored in the above-mentioned data types. This required data to be fetched might be located at the beginning, in between, or at the end of the data type. For accessing this data, Python provides us with the ‘slice()’ function. Python slice() function allows the user to return a specific range of values from a collection of stored data elements. Let us understand more about the Python slice() function along with few examples.

Definition

  • Python slice() function is a pre-defined Python function that returns a slice object that can be used to access specific data from strings, lists, tuples, etc. The slice object is used to specify how to slice the sequence of data.
  • Python slice() is a pre-defined function that is used to extract a subset of data elements or a subpart of data values that are stored in strings, tuples, lists, etc. as per the programmer’s needs.

Python slice() Parameters

The Python slice function generally accepts 3 parameters. These 3 parameters are separated using the comma (,) symbol. and they can be used using the following syntax –

                    

slice(start, stop, step)

where,

start Starting integer from where the slicing will start. If not declared, then its default value is None. This parameter is Optional.

stop Ending integer till which the slicing operation will take place.

step It is an optional parameter that determines the increment between each index for slicing.

Note If you mention only 1 parameter in the slice() function, then it is by default a ‘stop’ parameter. The other 2 parameters are considered to be ‘None’ i.e. their default values.

Python slice Objects

In order to use the slice() function, we need to create slice objects. Slice objects are used to specify how the sequence of data elements will be sliced. Using slice objects we can determine the beginning of the slicing operation and where it will end.

Let us look at an example where we create a slice object.

Example

                    

# Creating slice objects
slice(5)
a = slice(5)   # created a slice object where stop = 5
print(a)
 
b = slice(0, 6, 2)   # created slice object where start = 0, stop = 6 and step = 2
print(b)

Output

                    

slice(None, 5, None)
slice(0, 6, 2)

Get substring using Slice Object

After creation of Python slice objects, we need to assign them a value that can be used for further slicing process. Let us look at a program that demonstrates the Python slice() operator for a string data value.

Example

                    

str = 'Hello Beautiful World!'

# stop = 10
a = slice(10)
print(str[a])   # slices and prints values till index location 9

# start = 2, stop = 12
b = slice(2,12)
print(str[b])   # slices and prints values between index location 2 and 11

# start = 0, stop = 28, step = 4
c = slice(0,28,4)
print(str[c])   # slices and prints values between index location 0 and 27 with interval 4

Output

                    

Hello Beau
llo Beauti
HoafWd

Get Substring using Negative Indexing

Just as we use positive integers in the Slice function, we can also use Negative Index values. Negative Index values represent positions from the end of the string, list, tuple, array, etc.

Example

                    

str = 'Python Program' 

# stop = -6
a = slice(-6)
print(str[a])   # slices and prints values except last 6 index locations

# start = -1, stop = -16, step = 3 from the right side
b = slice(-1, -16, -3)
print(str[b])

Output

                    

Python P
mgPoy

Get Sub-List and Sub-Tuple

Lists in Python are denoted by the Square bracket ‘[]’ symbol whereas Tuples in python are initialized using Parenthesis‘()’. Lists are mutable objects which means their value cannot change once created. Whereas Tuples are immutable objects whose values can be changed after creation.

Example

                    

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
mytuple = ('H', 'E', 'L', 'L', 'O', 'G', 'U', 'Y', 'S')

a = slice(5)
print(mylist[a])   # slices values till position 5

b = slice(0, 7, 2)
c = slice(1, 7, 2)

print('Odd numbers: ', mylist[b])    # indices 0, 2, 4, 6 included
print('Even numbers: ', mylist[c])   # indices 1, 3, 5 included

x = slice(6)
print(mytuple[x])

y = slice(0, 10, 3)   # indices 0, 3, 6 included
print(mytuple[y])

Output

                    

[1, 2, 3, 4, 5]
Odd numbers:  [1, 3, 5, 7]
Even numbers:  [2, 4, 6]
('H', 'E', 'L', 'L', 'O', 'G')
('H', 'L', 'U')

Get Sub-List and Sub-Tuple using Negative Indexing

Negative Indexing can also be used to obtain sub-lists and sub-tuples in Python. It is similar to the Negative Indexing we perform on getting a substring.

Example

                    

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
mytuple = ('H', 'E', 'L', 'L', 'O', 'G', 'U', 'Y', 'S')

a = slice(-1, -9, -2)
print('Even numbers: ', mylist[a])   # indices 1, 3, 5, 7 included

b = slice(-1, -9, -3)   # indices 2, 5, 8 included
print(mytuple[b])

Output

                    

Even numbers:  [8, 6, 4, 2]
('S', 'G', 'L')

Indexing Method for Slicing

Another method for using the slicing function in Python is by using the Indexing syntax. We can substitute the slice object method with the Indexing syntax in Python. In the Indexing method, we use the ‘:’ symbol in between the parameters. The syntax is –

                    

obj_name [start: stop: step]

Example 1

                    

# Slicing using Indexing Method
num_list = [10, 43, 3, 53, 11, 68, 31, 93]

print(num_list[1:5])   # will start slicing from index 1 to index 4

print(num_list[:-3])  # will slice the last 3 elements and print remaining elements

print(num_list[:3])   # will slice upto 3rd element in the list

print(num_list[3:])   # will start slicing from 3rd element till the list ends

print(num_list[-3:])  # will slice and print last 3 elements of the list

Output

                    

[43, 3, 53, 11]
[10, 43, 3, 53, 11]
[10, 43, 3]
[53, 11, 68, 31, 93]
[68, 31, 93]

Example 2

                    

# Slicing of a string using Index Method
str = 'Hello World!'

print(str[0:4])   # prints values at indices 0, 1, 2, 3
print(str[0:12:2])  # prints values at indices 0, 2, 4, 6, 8, 10

Output

Frequently Asked Questions

Q1. What is slicing in Python?

Answer. Slicing in Python is a function that allows us to access parts of sequences like strings, tuples, lists, arrays, etc. We can specify where to start the sequence and where to end it.

Q2. How do you slice in Python?

Answer. Python provides the programmer with a built-in slice() function.  This python slice() function takes 3 parameters – start, stop and step. Its syntax is –

slice(start, stop, step)

The start parameter determines the starting point we want to start the slicing. The stop parameter denotes till where do we want to keep slicing. The step parameter determines the increment between each index for slicing.

Q3. What is slicing in lists in Python?

Answer. Slicing in lists is used to extract specific parts of the data stored in the lists into another list. We use 2 different methods for slicing of lists in Python –

1. Slice() function method

2. Slice Indexing Method

Example

                    

List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = slice(1, 9, 2)   # slice() function
print(List[a])

print(List[1:9:2])   # slice indexing method

Output

                    

[2, 4, 6, 8]

[2, 4, 6, 8]

Both the methods will produce the same output. In the first print statement, we first create a slice object and then pass it to the List. In the second print statement, we directly use the Indexing method to return the sub-list.

Q4. What is string slicing in Python with examples?

Answer. Python string slicing is a process where a substring is being extracted from a string. Just like Python list slicing, string slicing is also done in 2 ways –

Example –

                    

str = 'Python Rocks!'

a = slice(0, 14, 2)   # slice() constructor used
print(str[a])

print(str[1:14:3])   # slice Indexing method

Output

Q5. Why is Negative indexing used for slicing?

Answer.  The negative Indexing method is an alternative to the other Slice() method. Negative indexing lets the slicing take place from the right side of the data type. In negative indexing, -1 indicates the last character of the string, list, tuple, etc., -2 indicates next to the last, and so on.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.