Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such when strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python.
Indexing in Python
In the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python distinct is that Python also follows negative indexing which starts from -1. -1 denotes the last index, -2, denotes the second last index, -3 denotes the third last index, and so on.
Slicing with Negative Numbers in Python
In Python, we can perform slicing enabled iterable objects in two ways first is using list slicing and the second is using slice() function. Python also allows programmers to slice the iterable objects using negative indexing. Let’s first review the syntax of both methods.
- Using Slicing ( : )
- Using slice() Function
Slicing with Negative Numbers Using Colon ‘:’ Operator
We can perform slicing in Python using the colon ‘:’ operator. It accepts three parameters which are start, end, and step. Start and end can be any valid index whether it is negative or positive. When we write step when -1 it will reverse the slice.
text = "CodesForCodes"
# Slicing left part of string text
left = text[:-8]
# Slicing middle part of string text
middle = text[-8:-5]
# Slicing right part of string text
right = text[-5:]
print(left)
print(middle)
print(right)
Codes For Codes
In this example, we use the variable “text” to demonstrate string slicing. Slicing from the left starts from the beginning, and for the middle part, we specify indices. The right part is sliced similarly. The slices are stored in variables “left,” “middle,” and “right” respectively.
Syntax:
sequence[Start : End : Step]
Parameters:
- Start: It is the starting point of the slice or substring.
- End: It is the ending point of the slice or substring but it does not include the last index.
- Step: It is number of steps it takes.
Slicing with Negative Numbers Using slice() Function
slice() function/method is have used same when colon ‘:’ operator. In slice() function/method we passed the start, stop, and step arguments without using colon.
In this example, a string is stored in the variable “text,” and the `slice()` function/method is employed for string slicing. For the left part, an empty start indicates slicing from the beginning up to the index “-8,” stored in the variable “left.” The middle part is sliced by specifying indices -8 and -5. Similarly, the right part is obtained using the `slice()` function.
text ='CodesForCodes'
# Slicing left part of string text
left = text[slice(-8)]
# Slicing middle part of string text
middle = text[slice(-8,-5)]
# Slicing right part of string text
right = text[slice(-5,None)]
print(left)
print(middle)
print(right)
Codes for Codes
More Examples
Slicing List with Negative Numbers in Python
In this example, the code creates a list named “items” and utilizes slicing to extract specific items. By recognizing that the last four items represent vegetables, they are sliced and stored in the variable “vegies.” The same approach is applied to extract fruits, but this time the `slice()` function/method is have used for the slicing operation.
# Create a list
items = ["pen", "pencil", "eraser",
"apple", "guava", "ginger",
"Potato", "carret", "Chilli"]
# Slicing vegetables from list items
vegies = items[-4:]
print(vegies)
# Slicing fruits from list items
fruits = items[slice(-6, -4)]
print(fruits)
['ginger', 'Potato', 'carret', 'Chilli'] ['apple', 'guava']
Reverse List with the Negative Step
In this example, we have reversed the list using normal slicing and slice() function. Both of functions/methods are very similar we have to just pass the -1 in the third argument which is “Step” and passing nothing in normal slicing and “None” in the slice() function.
# Create a sample list
nums = [1,2,3,4,5,6,7,8,9,10]
# reverse the list using slicing
reverse_nums = nums[::-1]
print(reverse_nums)
# reverse the list using slice func
reverse_nums2 = nums[slice(None, None, -1)]
print(reverse_nums2)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Slicing Alternates in the List with Negative Step
In this example, we sliced the alternate items from list by passing “-2” in the step argument. We can review in the output that the printed slice is alternate numbers are printed by skipping one number.
# Create a sample list
nums = [1,2,3,4,5,6,7,8,9,10]
# Slice alternate items from last
alt_nums = nums[::-2]
print(alt_nums)
# Slice alternate items from last using slice func
alt_nums2 = nums[slice(None, None, -2)]
print(alt_nums2)
[10, 8, 6, 4, 2] [10, 8, 6, 4, 2]
Slicing Tuples with Negative Numbers in Python
In this example, below code shows distinct ways to cut a tuple. In the first two lines, it takes the last three items and items from the fifth to third from the end of the tuple. The last two lines reverse the tuple and pick every second item from the end using a specific method, creating new slices.
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
#Accessing the last three elements
slice = my_tuple[-3:]
print(slice)
#Accessing elements from the fifth-last to the third-last
slice = my_tuple[-5:-2]
print(slice)
# Reversing the tuple using negative step
reversed_tuple = my_tuple[::-1]
print(reversed_tuple)
# Using negative step to get alternate elements from the end
slice = my_tuple[::-2]
print(slice)
(7, 8, 9) (5, 6, 7) (9, 8, 7, 6, 5, 4, 3, 2, 1) (9, 7, 5, 3, 1)