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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read