Python list indexing from negative to positive indexes

Question:

I am trying to index from a list. I understand that negative indices refer to items counting backwards from the end of the list. My question is why it does not seem possible to index over a range starting from a negative index to a positive index, even though it seems intuitive.

For example, foo[-1], foo[0], foo[1] are all valid ways to index from the list foo. Why does foo[-1:1] not work?
Alternatively, since foo[-1:] selects the last element, why does foo[-1:0] not work equivalently?

foo = ['a','b','c']
print(foo[-1])
print(foo[0])
print(foo[1])
print(foo[-1:1])

It is possible to index directly from -1, 0, and 1, but not through that range -1:1.

Asked By: kcl

||

Answers:

you can do

foo[-1:1:-1]

output : ['c']

slicing uses foo[start:end:step]

you can do foo[::-1] to reverse the list etc.

Answered By: Derek Eden

As far as I can tell, you are looking for something like this:

a = [10, 20, 30, 40]
a[-1:] + a[:1]  # this is [40, 10]

You could make it behave like this automatically, but that would require a check if b > c when querying a[b:c] (keep in mind, that your -1 in the example is actually len(a) - 1).

Answered By: Emil Vatai

This will print all the elements in foo

print(foo[-len(foo):])

i.e.

['a', 'b', 'c']

This will print last two elements in foo

print(foo[-2:])

i.e.

['b', 'c']

That’s how it works

Answered By: Sameeresque
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.