used to in Python to begin slicing from the end of the string i.e. the last
In Python, a negative index refers to accessing elements from the end of a sequence, such as a list or a string. The last element in the sequence has an index of -1, the second-to-last element has an index of -2, and so on.
Here’s an example to illustrate the usage of negative indexing:
my_list = ['apple', 'banana', 'cherry', 'date'] Â print(my_list[-1]) # Access the last element print(my_list[-2]) # Access the second-to-last element
In the code above, we have a list my_list containing four elements. By using negative indexing, we access elements from the end of the list. my_list[-1] gives us the last element, which is 'date', and my_list[-2] gives us the second-to-last element, which is 'cherry'.
Negative indexing provides a convenient way to access elements from the end of a sequence without needing to know its exact length. It can be particularly useful when dealing with lists or strings of variable lengths or when you want to access elements in reverse order.
