I'm trying to find a way to get the index of an item in a list in Python given its negative index, including an index of 0.
For example with a list, l of size 4:
l[0] # index 0
l[-1] # index 3
l[-2] # index 2
I have tried using
index = negative + len(l)
however this will not work when the index is 0
.
The only way I have found so far involves an if/else
statement.
index = 0 if negative == 0 else negative + len(l)
Is there a possible way to do this in Python without having to use an if
statement?
I am trying to store the index of the item so I can access it later, but I am being given indices starting from 0 and moving backwards through the list, and would like to convert them from negative to positive.
Negative exponent rule: To change a negative exponent to a positive one, flip it into a reciprocal.
Python3. In this, we reverse the list using slicing, and use ~ operator to get negation, index() is used to get the desired negative index.
To recap, Python supports positive zero-based indexing and negative indexing that starts from -1. Negative indexing in Python means the indexing starts from the end of the iterable. The last element is at index -1, the second last at -2, and so on.
Negative Indexing is used to in Python to begin slicing from the end of the string i.e. the last. Slicing in Python gets a sub-string from a string. The slicing range is set as parameters i.e. start, stop and step.
index = index modulo size
index = index % len(list)
For a list of size 4, it will have following values for given indices :
4 -> 0
3 -> 3
2 -> 2
1 -> 1
0 -> 0
-1 -> 3
-2 -> 2
-3 -> 1
-4 -> 0
If you try to "go back" starting with a non-negative index, you can also use
index = len(l) - index - 1
to compute the "index from the back".
This is how you have to do it in many other programming languages. Pythons negative indices are just syntactic sugar.
But if you really use negative indices, this dirty hack is a one-liner without if
and else
:
index = int(negative != 0 and negative + len(l))
Explanation:
negative == 0
the result of the and
expression is False
which is converted to 0
by calling int
.and
is negative + len
, see also here. The call to int
then just does nothing.This is good for learning Python, but I usually avoid such tricks. They are hard to read for you and others, and maybe you want to read your program in a few months again and you then you will wonder what this line is doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With