Python, getting the last element with slice() object

Viewed 2192

How do i create a slice() object so that it would include the last element of a list/string

s = 'abcdef'
s[slice(2,4)]

works fine.
Say I wanted to get elements from second to the end, the equivalent of s[2:]

s[slice(2)]      # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)]     # same as above
s[slice(2, -1)]  # gives a range from second to the end excluding the last element
s[slice(2, 0)]   # gives empty as expected,  since end of range before the start

I can get specifically the last element with slice(-1, -2, -1), this won't work correctly for more then one element.

3 Answers

If you want to include the last element you can do that in the following two ways :

s[slice(2,6)]

or replace 6 with len(s)

Or you could also do:

s[slice(2,None)]

You can test it with magic method __getitem__. The last object can be get with slice(-1, None, None):

s = 'abcdef'

class A:
    def __getitem__(self, v):
        print(v)

a = A()
a[-1:]

print("s[-1:] = ", s[-1:])
print("s[slice(-1, None, None)] = ", s[slice(-1, None, None)])

Prints:

slice(-1, None, None)
s[-1:] =  f
s[slice(-1, None, None)] =  f

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

So you can just use:

s= "abcdef"
print(s[-1])

Result:

f
Related