Reputation: 146
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.
Upvotes: 5
Views: 4555
Reputation: 705
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)]
Upvotes: 6
Reputation: 195418
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
Upvotes: 2
Reputation: 5121
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
Upvotes: 1