Slicing with Negative Numbers in Python
Last Updated :
02 Dec, 2024
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as 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 different 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 on 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 see 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 as -1 it will reverse the slice.
Python
text = "GeeksforGeeks"
# 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)
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 is used same as colon ':' operator. In slice() function 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 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.
Python
text = "GeeksforGeeks"
# 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)
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 is used for the slicing operation.
Python
# 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)
Output['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 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.
Python
# 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)
Output[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 see in the output that the printed slice is alternate numbers are printed by skipping one number.
Python
# 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)
Output[10, 8, 6, 4, 2]
[10, 8, 6, 4, 2]
Slicing Tuples with Negative Numbers in Python
In this example, below code shows different 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.
Python
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)
Output(7, 8, 9)
(5, 6, 7)
(9, 8, 7, 6, 5, 4, 3, 2, 1)
(9, 7, 5, 3, 1)
Similar Reads
numpy.negative() in Python
numpy.negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar. Syntax : numpy.negative(arr, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, ext
2 min read
What are Positive and Negative Numbers?
Numbers are the mathematical values or figures used for the purpose of measuring or calculating quantities. It is also represented by numerals as 3, 4, 8, etc. Some other examples of numbers are whole numbers, integers, natural numbers, rational and irrational numbers, etc. The system includes diffe
4 min read
How to Add Fractions with Negative Numbers?
As we know addition is the basic operation of mathematics. It is used to find the sum of two positive or negative numbers. We can also add fractions with the same or different denominators. We are also allowed to add fractions with negative numbers. Some rules we need to remember when we perform add
5 min read
JS Equivalent to Python Slicing
In Python, slicing is a feature that allows us to extract portions of a sequence such as lists, strings and tuples using a simple syntax. However, JavaScript does not have a direct equivalent to Pythonâs slicing syntax. Fortunately, there are several ways to achieve similar functionality in JavaScri
4 min read
How to add positive and negative numbers?
Algebra is a special branch of mathematics that is used to deal with the arithmetic operations, such as addition, subtraction, multiplication, or division, and the associated symbols, also known as variables. The variables are not fixed and change their value. Some of the examples of variables are x
4 min read
Python | Replace negative value with zero in numpy array
Given numpy array, the task is to replace negative value with zero in numpy array. Letâs see a few examples of this problem. Method #1: Naive Method C/C++ Code # Python code to demonstrate # to replace negative value with 0 import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing i
4 min read
What is the rule for subtracting negative numbers?
Answer: When a negative number is subtracted from a negative number, a minus sign followed by a negative number turns into a plus sign.Algebra is the branch of mathematics dealing with arithmetic operations and its associated symbols. The symbols are termed as variables that may take different value
6 min read
Can negative numbers be whole numbers?
Negative numbers are not whole numbers since whole numbers are defined as non-negative integers, which contain 0 and all positive integers (1, 2, 3, and so on). Whole numbers are used to count items that cannot be broken down into smaller pieces or fall below zero, such as objects or quantities. Neg
6 min read
How to perform modulo with negative values in Python?
Taking the modulo of a negative number is a bit more complex mathematics which is done behind the program of Python. If we don't understand the mathematics behind the modulo of negative numbers then it will become a huge blunder. Mathematics behind the negative modulo : Let's Consider an example, wh
3 min read
numpy.signbit() in Python
numpy.signbit(array, out = None, where = True, casting = âsame_kindâ, order = âKâ, dtype = None) : This mathematical function helps user to element - wise check whether the signbit is set or not. Parameters : array : [array_like]Input array or object whose elements, we need to check. out : [ndarray,
2 min read