kcl
kcl

Reputation: 23

Python list indexing from negative to positive indexes

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.

Upvotes: 1

Views: 1073

Answers (3)

Emil Vatai
Emil Vatai

Reputation: 2531

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).

Upvotes: 0

Sameeresque
Sameeresque

Reputation: 2602

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

Upvotes: 0

Derek Eden
Derek Eden

Reputation: 4618

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.

Upvotes: 2

Related Questions