Python Slicing | Python slice() Constructor

What is Slicing in Python?

In Python, iterables are objects that support sequence protocol. Some examples of iterables include strings, lists, sets, and tuples. All iterables are indexed starting with zero from left to right. When working with these iterables, we often need to obtain only a certain part of an iterable rather than the whole iterable. This process of extracting a subset of values from an iterable is called slicing. In Python, slicing is done with the help of a constructor called slice().

Indexing in Python

To get values from an iterable, there are two techniques to index an iterable in Python, one is called Positive Indexing and the other is called Negative Indexing.

Positive indexing is the indexing that starts from the left and with the value 0. It is easier to use positive indexing when accessing elements from the left.

Negative indexing is the indexing that starts from the right and with the value -1. It is easier to use negative indexing when accessing elements from the right.

The below table shows the two types of indexing in Python.

Positive Indexing 0 1 2 3 4
String H E L L O
Negative Indexing -5 -4 -3 -2 -1

For example, to get the character “E” from the string “HELLO”, we can either use positive indexing or negative indexing.

Example of using indexing in Python

word = "HELLO"
print(word[1])
print(word[-4])

Output

E
E

In the above code example, [] is the indexing operator that we use to pass our index values. This operator is useful for both getting a value from an iterable and for slicing an iterable.

Slice() in Python

It is a constructor that creates a slice object. It has the following three parameters:

  • start – The integer at which the object slicing begins. This is optional and the default value is None.
  • stop – The integer at which the object slicing ends. This is optional and the default value is -1 which is the index of the last element.
  • step – The increment between each index for slicing is determined by this parameter. If no value is specified, it defaults to None.

To create a slice object, we use the following syntax:

Syntax

slice(start, stop, step)

Example of creating slice objects in Python

a = slice(1, 10, 2)
print(a)
print(type(a))

Output

slice(1, 10, 2)
<class ‘slice’>

In the above code example, we have created a slice object. We can use this object to slice iterables.

Examples of Using the Slice Object in Python

We can use the slice objects in various ways to slice an iterable. The following code examples will help us get a detailed understanding of different ways of slicing an iterable.

Slicing a string using positive index

word = "PythonGeeks"

obj1 = slice(0, 11)  # start = 0, stop = 11
obj2 = slice(6)  # stop = 6
obj3 = slice(1, 11, 2) # start = 1, stop = 11, step = 2

print(word[obj1])
print(word[obj2])
print(word[obj3])

Output

PythonGeeks
Python
yhnek

Slicing a string using negative index

word = "PythonGeeks"

obj1 = slice(-1, -12, -1)
obj2 = slice(-5)
obj3 = slice(-2, -10, -2)

print(word[obj1])
print(word[obj2])
print(word[obj3])

Output

skeeGnohtyP
Python
kenh

Slicing a list using positive index

li = [1, 2, 3, 4, 5]

obj1 = slice(0, 5) 
obj2 = slice(4) 
obj3 = slice(2, 5, 2)

print(li[obj1])
print(li[obj2])
print(li[obj3])

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[3, 5]

Slicing a list using negative index

li = [1, 2, 3, 4, 5]

obj1 = slice(-1, -6, -1)
obj2 = slice(-3)
obj3 = slice(-1, -6, -2)

print(li[obj1])
print(li[obj2])
print(li[obj3])

Output

[5, 4, 3, 2, 1]
[1, 2]
[5, 3, 1]

Indexing Syntax for Slicing in Python

Python provides a more convenient way of slicing. We can simply replace the slice object with an indexing syntax. This method eliminates the need for calling the slice() constructor every time we need to slice an object. This saves time and makes our code look simple and easily readable The following is the Indexing Syntax:

Syntax

object[start: stop: step]

Example of using indexing syntax in Python

word = "PythonGeeks"

print("Positive Indexing")
print(word[:11])
print(word[0:10])
print(word[1:11:2])
print(word[::2])
print(word[2:])

print("\nNegative Indexing")
print(word[-1:-11:-1])
print(word[:-10:-2])
print(word[-2:-8:-3])
print(word[-11:])
print(word[-11:-2])

Output

Positive Indexing
PythonGeeks
PythonGeek
yhnek
PtoGes
thonGeeksNegative Indexing
skeeGnohty
seGot
kG
PythonGeeks
PythonGee

Changing the Length of Iterables in Python

We can also change the length of an iterable through slicing. To do this, we need to replace the original iterable with the sliced iterable.In Python, this is the most popular method of resizing an iterable.

Example of slicing to change the length of an iterable in Python

li = [1, 2, 3, 4, 5, 6, 7]  # original length is 7
li = li[:3] # changing length to 3
print(li) 

Output

[1, 2, 3]

Deleting Values of Iterables in Python

By using the del keyword along with slicing, we can delete multiple values at once in an iterable. This does not work for strings.

Example of deleting values of an iterable in Python

li = [1, 2, 3, 4, 5, 6, 7]

del li[:3]
print(li)

Output

[4, 5, 6, 7]

Python Interview Questions on Slicing

Q1. Write a program to create a string containing the first three letters of the string “Mango”.

Ans 1. The complete code is as follows:

str1 = "Mango"
str2 = str1[:3]
print(str2)

Output

Man

Q2. Write a program to create a string containing the last two letters of the string “Beautiful”

Ans 2. The complete code is as follows:

str1 = "Beautiful"
str2 = str1[-3:]
print(str2)

Output

full

Q3. Write a program to print a given string in reverse.

Ans 3. The complete code is as follows:

str1 = input("Enter a word: ")
str2 = str1[::-1]
print(str2)

Input
Enter a word: America

Output

aciremA

Q4. Write a program to print only the odd index values from the list [11, 12, 2, 14, 10, 3]. We consider zero to be even in this case.

Ans 4. The complete code is as follows:

list1 = [11, 12, 2, 14, 10, 3]
print(list1[1::2])

Output

[12, 14, 3]

Q5. Write a program to print only the even index values in reverse from the list [4, 8, 7, 6, 5, 4, 3, 2, 1]. We consider zero to be even in this case.

Ans 5. The complete code is as follows:

list1 = [4, 8, 7, 6, 5, 4, 3, 2, 1]

print(list1[-1:-len(list1)-1:-2])

Output

[1, 3, 5, 7, 4]

Quiz on Python Slicing and Slice() Constructor

Conclusion

In this article, we learned about the slice constructor and its different use cases. We learned how to use the negative indexing to get objects in reverse. Then we also learned about resizing the iterables and deleting subsets from iterables. We discussed the most common way of slicing and how it is more convenient than using a constructor. Furthermore, if you have any comments, feel free to write them in the comments section.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *