Python Slicing

Python slicing is a process of acquiring a substring by slicing it from the provided string from initial phase to the end phase.

What Is Slicing?

Slicing is a process in computer science background when an objecj specifies the method of slicing a sequence. In this whole process, a user is able to specify where slicing should start and where he should end it. Along with this, the user will be allowed to specify all the steps and slice every other item.

Become a Python Certified professional by learning this HKR Python Training!

Python Slicing

Python slicing is a process of acquiring a substring by slicing it from the provided string from initial phase to the end phase. A substring can be in any form such as string, tuples, list, range, etc.

This process can be done in two ways:

  • slice() constructor
  • Extended Indexing

Below is a python code to understand slicing:

text = 'HKR Trainings'


slice_text = slice(4)

print(text[slice_text])


Output:

HKR

As we can understand from the code above, we can observe the syntax of slicing:


slice(start, step, stop)

Let us see how these parameters work with python:

Slice Parameters

start:  This is the point where the slicing of the object will start. This will be default to none if the start point of slicing is not mentioned.
step(): This is the point where the value will be incremented at each point. This will be default to none if the start point of slicing is not mentioned.
stop():  This is the point where the slicing of the object will stop as specified by a range.

Let us see an example below to get a substring using negative index in python:


py_string = 'HKR Training'


sliced_object = slice(-1, -3, -1)


print(py_string[sliced_object]) 




Output:

gn

Let us see an example now which demonstrates slicing of a string in python: 


String ='HKR TRAINING'

sl1 = slice(3)

sl2 = slice(1, 5, 2)

sl3 = slice(-1, -12, -2)


print("String slicing is performing")

print(String[sl1])

print(String[sl2])

print(String[sl3])




Output:

String slicing is performing

HKR



GIIR R

Now let us see another example below to get a substring using slice object


py_string = 'HKR Trainings'

sliced_object = slice(3) 

print(py_string[sliced_object])  


# start = 1, stop = 5, step = 3

sliced_object = slice(1, 5, 3)

print(py_string[sliced_object])




Output:

HKR

RT

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

What Is an Index?

A position of a specific character or let's say an item present in a list, string or a tuple is termed as index. The value of an index also initiates from zero ending at one less than the specified number of elements in the respective list, string or the tuple. 

Let us see an example how indexing is done with slicing in python:

py_string = 'HKR trainings'


print(py_string[0:2])  


print(py_string[1:5:2]) 


Output:

HR

R
There are also negative indexes which can enable a programmer to index a list, or a tuple to index from the end and not from the start of the list. 
name ="HKR TRAINING"

print(name[-5:-2])


list1= [10,20,30,40,50,60]

print(list1[-6:-2])


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

print(tuple1[-4:-1])

 


Output:

INI

[10, 20, 30, 40]

[4, 5, 6]

Extended Indexing

Extended Indexing can be used as an alternative for slicing an object in python. This is an easy process and the most appropriate way to slice an item including its syntax and execution both. This process is most feasible to work with strings. 


Syntax: [start:end:step]


These 3 steps start, end and step work in the same way as described for slice() constructor above.

Let us see an example in python demonstrating how extended indexing works:

String ='Welcome to HKR'

  

print(String[:2])

print(String[1:4:2])

print(String[-1:-11:-2])

  

print("\nReverse String will be")

print(String[::-1])


Output:

We

ec

XHo m


Reverse String will be

RKH ot emocleW

>
If you want to Explore more about Python? then read our updated article - Python Tutorial.

Subscribe to our youtube channel to get new updates..!

Specify Step By Step Slicing Process

Steps of Slicing

There is a method of step slicing in python where if a user wants to skip a few items in the code, he can simply follow step slicing. Let us understand this better using a python code below:

String ='Welcome to HKR'

print(String[1:6:2])


list1 =[10,20,30,40,50,60]

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


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

print(tuple1[-4:-1:2])


Output:

ecm

[10, 30, 50]

[4, 6]

As we can clearly see in the above example, the string ‘Welcome to HKR’ is sliced one through six from the indexes. However, in this case the step size for slicing was set as two, the user receives every second character in the output initiating from the initial index. In case it was set to 3, the user would have received the output initiating from the initial index.

Reversing the elements

This is done by using a negative step for reversing the items of a data structure in python. Let us understand this more clearly using with a python code below:

x ="Welcome" "to" "HKR"

print(x[::-1])


y= "HKR" 

print(y[::-1])


z =(1,2,3,4,5,6,7)

print(z[::-1])


Output:

RKHotemocleW

RKH

(7, 6, 5, 4, 3, 2, 1)

>

Slice Function in Python

The slice() function in python tends to extract a specific part of data and returns it in the form of fresh data. This whole process takes place without modifying the data. This allows the programmers to take up a specific range of elements without making any changes to it.

Let us see an example in python demonstrating how slice() function works in python:


String ='Welcome to HKR'

x= slice(1,4)

print(String[x])


list1 =[10,20,30,40,50,60]

y= slice(1,4)

print(list1[y])


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

z= slice(1,4)

print(tuple1[z])


Output:

elc

[20, 30, 40]

[2, 3, 4]

>

Top 30 frequently asked Python Interview Questions!

Insertion and Deletion using Slicing

Insertion using Slicing 

It is possible for programmers to insert objects into a list. This is done without even replacing already stored objects in the list. 

Let us see an example of how a user can perform insertion in a list using slicing in python:

String ='Welcome to HKR'

x= slice(1,4)

print(String[x])


list1 =[10,20,30,40,50,60]

y= slice(1,4)

print(list1[y])


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

z= slice(1,4)

print(tuple1[z])


Output:

elc

[20, 30, 40]

[2, 3, 4]

>
Deletion using Slicing

It is possible for programmers to delete objects from a list or even multiple objects simply by using del function.

Let us see an example of how a user can perform deletion in a list using slicing in python:

from array import *


arr= array('i',[10,20,30,40,50])

arr.remove(10)

print(arr)




Output:

array('i', [20, 30, 40, 50])

Python Training Certification

Weekday / Weekend Batches

 Conclusion

In this article, we have understood the meaning of slicing and how we can conduct slicing with the help of python. We have also discussed indexing in python, slicing with negative index as well as insertion and deletion in python. You will also understand the use of the slice() function in this article. We have also elaborated on how the process of slicing, negative slicing method as well as step-indexing works through various examples. Both concepts are essential for understanding Python. 

This all is designed to help you get thorough with the concepts of slicing along with its examples. 

Related Articles

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 30th Sep 2022, Fast Track batch

  • Batch starts on 4th Oct 2022, Weekday batch

  • Batch starts on 8th Oct 2022, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.