Slicing tuples backwards - how to deal with the first element?
Let's say I need elements 1-3 of a tuple, back:
x = (0,1,2,3,4)
x[1:4]
Returns (1,2,3)
and
x[3:0:-1]
Returns (3,2,1)
But what if I want items 0-2?
I can do x[2::-1]
to get the correct answer (2,1,0)
, but it x[2:0:-1]
returns (2,1)
and x[2:-1:-1]
returns ()
.
Is there a way to cut off the last element without using an operator if
if I cut it at unknown intervals?
One slightly inefficient way:
x[0:3][::-1]
Which is equivalent:
tuple(reversed(x[0:3]))
I'm not sure how well the unneeded intermediate tuple will be optimized.
Instead of an empty element, you can use None
:
x[2:None:-1]
with x[-n:]
you can get the last index n
, and with with [::-1]
you can invert it!
>>> x[-2:][::-1]
(4, 3)
>>>
Possibly merging a reverse-frequent tuple with your original tuple and an index that:
>>> x = (0, 1, 2, 3)
>>> y = (0,)
Then:
>>> (y + x)[3:0:-1]
(2, 1, 0)
>>> (y + x)[2:0:-1]
(1, 0)
Not as fast as Peter DeGlopper's solution:
#!/usr/bin/env python
import time
x = tuple(range(0,int(1e6)))
y = (0,)
start_time = time.time()
a = (y+x)[3:0:-1]
print("tuple add --- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
b = x[0:3][::-1]
print("tuple rev --- %s seconds ---" % (time.time() - start_time))
Not even close, really:
$ ./test61.py
tuple add --- 0.0153260231018 seconds ---
tuple rev --- 6.19888305664e-06 seconds ---