Python lists can be indexed in a variety of ways, including positive and negative numbers. This article will discuss how to use the “-” minus parameter to access specific elements in a list.
Basic List Structure and Operations
A list is defined using square brackets and elements within them. Each element is separated with the help of a comma.
list_name = [element_!, element_2, ..., element_n]
int_list= [3, 4, 5, 5, 6] # a list containing all integers char_list = ['a', 'b', 'c', 'd'] # al list of characters str_list = ["apple", 'banana', 'lemon', 'orange'] # a list of strings
What Are List Indexes?
Indexing is the fundamental unit of any linear data structure in any programming language. For every computer, the default index started from 0 and goes on till n-1. Here n denotes the total number of elements in the respective data structure. Types are:
- Positive indexing: Starts from 0 and increases
- Negative indexing: starts from the last element and movement is from tail to head with each traversal.
These help us to access the individual elements of this data structure. Let us see the operations in the next section.
Negative Indexes in Lists
This is the main point of focus on our topic. The “-1” parameter in lists is to denote the Python interpreter that operations are from the last element. First, we shall see how we can access the elements using the index numbers.
Using Negative Indexes to Retrieve List Data
my_list = [45, 5, 33, 1, -9, 8, 76] print(my_list[-1]) print(my_list[-2]) print(my_list[-3])
76 8 -9
Reversing the List With Negative Index
Using built-in function “reverse()”:
my_list = [45, 5, 33, 1, -9, 8, 76] my_list.reverse()
[76, 8, -9, 1, 33, 5, 45]
Reversing the list using -1
my_list = [45, 5, 33, 1, -9, 8, 76] my_list[::-1]
[76, 8, -9, 1, 33, 5, 45] # reversed list
Removing Elements With Negative Index
Using the pop() function and giving -1 as parameter inside it we can remove the last element of that list and we get a new list.
my_list = [45, 5, 33, 1, -9, 8, 76] my_list.pop(-1) my_list
76 # popped out element [45, 5, 33, 1, -9, 8] # new list returned
Advantages of Using Negative Indexing in Python List
- Reduces the lines of code and makes reverse in one line.
- Makes complex operations easier.
- Takes minimum time to operate providing less complexity.
This concludes our tutorial on Python negative indexing. We hope you found it helpful! If you have any questions or comments, please feel free to share them below. Thanks for reading!