Slicing of Sequences in Python

Hey learners! Welcome to the following lecture on Python, where all the examples are practically explained with the help of the Jupyter notebook. We have been working with the data types for a long time, and now we know all the basics about them. There are certain concepts that are applicable to almost all sequences, but there are some rules for performing this function. Python has many concepts that are unique and simple, and if we talk about the slicing of the data type, other high-level languages such as C++ have the same concept, but Python gives the easiest way to do so. How we will work on different data types to check whether they support the slicing or not. In this way, we can revise the concept that we have been working on so far. Nevertheless, before that, you have to check the list of content given next:

  • What is "slicing" in Python?

  • Can we slice any sequence?

  • What are the methods to use for the slicing process?

  • How do we use the colon to slice the lists?

  • Describe the process of using the colon in different ways and slice the sequence.

  • How do we use the slicing function on the arrays?

  • Can we use Numpy to slice the sequence?

  • How do you slice the tuple for slicing the sequences?

What is the Slicing of Sequence in Python?

We are all familiar with the slicing of bread, and the same concept is related to the slicing of a sequence with the help of different procedures. As we sliced the things and then picked the required ones for our usage, in this lecture we will slice the sequences(that are mutable or immutable in different ways). It is an important concept in programming especially if we talk about Python. There are different ways to introduce the slicing of data types:

"Slicing is a mechanism in Python that allows you to extract a portion (or a subset) of a sequence, such as a string, list, or tuple."

Slicing allows you to extract a portion of a sequence by specifying the start and end indices, allowing you to extract a contiguous portion of the sequence. There are different ways of slicing the data types, and we will go through all the important types that we have learned in this course. 

Methods of Slicing Data Types

There are certain ways to perform the same operation in a different way while you are programming. This is a plus point of Python it provides programmers to work in uncomplicated ways. People with prior experience in programming will find it super easy to slice the data types. There are two options for using the slicing mechanism mentioned below:

  1. Slicing through colon

  2. Slicing through function

There are still more types and ways to perform these functions, and we will try our best to perform all of you to show you the perfect way for every type of slicing you want according to your requirements. Moreover, it becomes easy to perform the complex problems when you know more than one solution in programming.

Slicing of Lists in Python

The first data type that will be sliced here is the list. We know lists are described by square brackets, and in Python, slicing of the list is a common practice because a large amount of data is stored in the lists; therefore, to perform efficient operations, we need the slicing often. The first example of the slicing of sequences is given next:

Slicing With Colon

This is the first style of slicing a sequence with the help of a colon. It is the simplest way to use the colon for slicing a long sequence, and the following syntax is used in it:

Name=[start;end]

Where,

name = "Name of the sequence declared before using this function."

start= It denotes the starting point for our sequence.

end: The point at which our chosen area must come to an end.

So let's try the example to check the results. 

Code:

#starting a new list to be sliced

myList = [22,8,11,9,44,11,22,89,4,90]

#slicing the list from the first to the fourth element

result=myList[1:4]

#printing the results

print("The sliced list= ", result)

Output:

Hence, only a small portion is obtained as expected. 

Slicing of List with Colon and Step Size:

We have seen a simple example till now but what if we want the variation? Programming is not an easy job and not every time do we need to simply put the portions of a list into different programs, but most of the time we have to pick the specific entries of the lists. For this, Python has another option for programmers. Simply by adding another parameter to the previous case, we can get the variations in the results according to our choice in the following way:

Code:

#starting a new birthday party list to be sliced

myList = ["balloons", "party hats", "cake", "candle", "drinks", "plates"]

#slicing the list to get from the first six elements at the step size of two elements

result=myList[1:6:2]

#printing the results

print("The sliced list= ", result)

Output:

Hence, in this case, we have seen the list in which the items from the birthday party were saved, and we wanted to get a final list that had the items from the parent list by ignoring the odd indexed elements and printing only the even indexed elements. We have taken this simple example to make sure you get the concept of the difference between the types of slicing discussed so far. 

Using the Double Colon in Python

If you have run the previous code, has the question popped into your mind as to what the other way to do so is? Well, yes, as we always say, programming gives you multiple options. If, in any case, the programmer is not able to use the start and end points and wants the whole sequence with steps, the other way to do so is to use the double colon. The simple code is given next:

Code:

#starting a new list with a string message in it to be sliced

myList = ["Hello", "we", "are", "programmers"," and", "we", "are", "interested", "in", "Python"]

#slicing the list to get the whole set with three steps till the end.

result=myList[::3]

#printing the results

print("The first four elements= ", result)

Output:

Here the procedure is simple and we are getting the required elements according to the need.

Slicing of the Sequence with Negative Indices

Another method to get the same results as in the first case is to use the negative indices. This option may seem different and weird, but in programming, having more options for the same task gives programmers more opportunities to use their creativity in a different way. Let’s prove this with an example:

Code:

#starting a new list with the floats in it to be sliced

myList = [23.8,44.8, 120.7, 226.90, 11.7, 118.90,12.55,1.3,77.3,119.1,23.90,31.66,119.4,12.65,11.4]

#slicing the list to get the 6th to 1st element from the end.

result=myList[-6:-1]

#printing the results

print("The sliced list= ", result)

Output:

Hence, the programmers can access the data from any side of the sequence easily, according to their needs. This way to slice the arrays has many interesting and fantastic applications in image processing.

Slicing the Sequence with Only One Value

The next type to be discussed is the one where only one number and one column are enough to slice the element. The limitation of this method is that the output contains all the elements from the side we started to the ending point, or, as we can say, this is the best way to get the left or right part of the sequence by using merely the starting or ending point and using the colon. The syntax to do this is

  1. Name[start:]

  2. Name[:end]

Here, two cases are discussed. Take the example of a long list where the requirement is to obtain the first five elements only, then the following code will be used:

Code:

#starting a new list with a string message in it to be sliced

myList = ["Hello", "we", "are", "programmers"," and", "we", "are", "interested", "in", "Python"]

#slicing the list to get the first four elements from the end.

result=myList[:4]

#printing the results

print("The first four elements= ", result)

Output:

As you might expect, the next case is diametrically opposed to the one just discussed. If a person wants to get the second half of the same message, then we have to count ourselves and enter the number of elements that we want to print from the end. 

Code:

#starting a new list with a string message in it to be sliced

myList = ["Hello", "we", "are", "programmers"," and", "we", "are", "interested", "in", "Python"]

#slicing the list to get the last five elements from the end.

result=myList[5:]

#printing the results

print("The first four elements= ", result)


Output:

Hence, the result we wanted to get is here on the screen. This gives a quick and easy way to print the entire length of the sequence. 

Slicing with Function

To slice the sequence, there is a special function that we have also mentioned in this lecture. Using the function is uncomplicated; just feeding the data is in the function's syntax, and the programmers do not need any special declarations before it. The procedure is the same as what we have discussed so far, and therefore, to make things simple, we will use the single code for different types of applications in the slice function. 

Code:

#importing the double array from the NumPy library

import numpy as NumPy

#decalring the new array

myArray = NumPy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

#Printing the first to the fourth index of the array using the slice function

result=myArray[0, 1:4]

print("Result= ", result)

#slicing both arrays at the same time and printing output

result=myArray[0:2, 1:5]

print("Result= ", result)


Output:

The following points are an extraction of the contents of this code:

  • The library in NumPy can be used to slice the sequences.

  • The double array is possible to import from NumPy.

  • The slicing of an array is possible using NumPy.

  • It is up to the programmer if he wishes to get the result from the single array or both of the arrays.

  • The index is used in the slice function, but not the position.


Slicing the Tuple Using Slice()

A tuple is another sequence that can be sliced. The procedure is the same, but we will use different ways to use the function in this example. 

Code:

#creating a new tuple having different data types in it

tuple = ("apple", "balloons", 32.2, "cat",12, "dog", "ear",23,"fruits","guitar","hen",1)

#using the slice function to get the third and fifth elements only

x = slice(3, 5)

print("Element at index three and five= ", tuple[x])

#using the slice function with the steps to get the required output

x = slice(1, 7, 3)

print("Sliced the tuple to get the result using step function= ", tuple[x])


Output:

Hence, tuples can easily be sliced using the function, and we have used it here because we wanted to save multiple types of data in the same sequence. 

Consequently, it was an informative lecture with a lot of examples and concepts. The start was full of an introduction to the slicing process and why we need the slice function in Python programming. After that, we learn different ways to use the colon for slicing. Although the concept was sometimes discussed in the previous lectures as well as here, we purely focused on the slicing, and it was interesting to see the examples of different data types such as sets, arrays, and tuples. We have a lot to learn in Python, so stay with us for the next lecture.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir