0

so i have a tuple in python and i need to slice from the last element to first element but only want the last and first...

example:

big tuple: (1,2,3,4,5)

i want to slice the tuple so i end up with (5,1)

some_list[::len(some_list)-1]

above code slices from first to last and only includes the first and last..taken from here! so i need the exact opposite.

Community
  • 1
  • 1
3MIN3M
  • 69
  • 1
  • 1
  • 9

3 Answers3

3

This code works:

some_list[-1:-len(some_list)-1:-(len(some_list) - 1)]

Another way:

some_list[::-len(some_list) + 1]

Of course you always can do

x[::len(x) - 1][::-1]
Drino
  • 91
  • 2
1

Why not just do

new_list = (some_list[-1], some_list[0])

?

metatoaster
  • 17,419
  • 5
  • 55
  • 66
  • while simple indexing is alot easier to read/understand its not what i needed in this case :) – 3MIN3M Apr 09 '14 at 00:28
  • You also haven't told us what exactly you are trying to solve and why are you doing what you are doing, so that's answers you might get. – metatoaster Apr 09 '14 at 00:30
  • yes you are right, i realize this isnt a very helpful question so is there a way to get it deleted? – 3MIN3M Apr 09 '14 at 00:34
  • 1
    It's okay, quite often we are intuitive in a way in pointing out a solution, but as I said without knowing exactly what your data/function override actually are we can't really say for sure that your way is inadequate or other suggested ways are correct. Still good enough as a reference though. – metatoaster Apr 09 '14 at 00:46
0
a = (1,2,3,4,5)    
print(a[0],a[-1])

Please try this. It has worked for me and seems to be a simple solution.

naninuneno
  • 23
  • 1
  • 5