Why do python list with a single entry give the 0th element for -1 index and 0 index?
Question:
On creating a list in python with just one element, when I try to get the -1 index element instead of getting list index out range error it is giving the 0th element.
some = ['something']
print(some[0]) # prints something
print(some[-1]) # prints something
Here is a link to the same:
https://repl.it/@hearsid/SuperiorProudShoutcast
Answers:
A negative index means nth from the right. The zero-index of a one-element list is the same as the negative-one-index of a one-element list because the zeroth element is the same as the first element from the right.
On creating a list in python with just one element, when I try to get the -1 index element instead of getting list index out range error it is giving the 0th element.
some = ['something']
print(some[0]) # prints something
print(some[-1]) # prints something
Here is a link to the same:
https://repl.it/@hearsid/SuperiorProudShoutcast
A negative index means nth from the right. The zero-index of a one-element list is the same as the negative-one-index of a one-element list because the zeroth element is the same as the first element from the right.