Slicing with Negative Numbers in Python

Negative slicing in python

Slicing in Python with negative indexes

Slicing with Negative Numbers in Python is a subpart of slicing in python. Slicing is used to iterate through the sequential or iterable data-type in the python programming language. In these Section, we will look at the slicing on some iterable or sequential data-types like:

  • List
  • String
  • Tuple

We will use negative indexes to slicer the elements of the data-types.

Slicing with negative numbers in Python

Slicing with Negative Numbers in Python

Python code for slicing with negative indexes

Slicing in String with negative indexes

The string is a data-type belongs to sequence data-type category. Slicing in the string is used to iterate through the elements. We have negative as well as negative indexes of any iterable data-type. In the below python code we will be iterating through negative indexes of the string elements.

#Initialize the String
String = 'PrepInsta'

#Slicing using 1 negative index
arr = String[-2:]
print(arr)

#Slicing using 1 negative index
arr = String[:-3]
print(arr)

#Slicing using 3rd negative index
arr = String[::-1]
print(arr)

#Slicing using 2 negative indexes
arr = String[-9:-4]
print(arr)
Output:
ta
PrepIn
atsnIperP
PrepI
#Initialize the String
String = ['P', 'r', 'e', 'p', 'I', 'n', 's', 't', 'a']

#Slicing using 1 negative index
arr = String[-2:]
print(arr)

#Slicing using 1 negative index
arr = String[:-3]
print(arr)

#Slicing using 3rd negative index
arr = String[::-1]
print(arr)

#Slicing using 2 negative indexes
arr = String[-9:-4]
print(arr)

Slicing in List with negative indexes

The list is a data-type in Python programming language. Slicing is an iterable data-type and so we can perform some slicing operations on the string. Slicing is done using indexes of the iterable. Here we will iterate through the list using the negative indexes.

Output:
['t', 'a']
['P', 'r', 'e', 'p', 'I', 'n']
['a', 't', 's', 'n', 'I', 'p', 'e', 'r', 'P']
['P', 'r', 'e', 'p', 'I']

Slicing in Tuple with negative indexes

Tuple data type is sequential data-type in python programming. A tuple is an immutable data-type. But we can perform many operations on the tuple. As it is an iterable data-type we can perform some slicing functions on the tuple. Let’s have a look at the python codes for slicing on the tuple.

#Initialize the String
String = tuple(['P', 'r', 'e', 'p', 'I', 'n', 's', 't', 'a'])

#Slicing using 1 negative index
arr = String[-2:]
print(arr)

#Slicing using 1 negative index
arr = String[:-3]
print(arr)

#Slicing using 3rd negative index
arr = String[::-1]
print(arr)

#Slicing using 2 negative indexes
arr = String[-9:-4]
print(arr)
Output:
('t', 'a')
('P', 'r', 'e', 'p', 'I', 'n')
('a', 't', 's', 'n', 'I', 'p', 'e', 'r', 'P')
('P', 'r', 'e', 'p', 'I')

To learn more  about slicing in python programming languege