Is there a way to slice only the first and last item in a list?
For example; If this is my list:
>>> some_list
[\'1\', \'B\', \'3\', \'D\',
def recall(x):
num1 = x[-4:]
num2 = x[::-1]
num3 = num2[-4:]
num4 = [num3, num1]
return num4
Now just make an variable outside the function and recall the function : like this:
avg = recall("idreesjaneqand")
print(avg)
first, last = some_list[0], some_list[-1]
I found this might do this:
list[[0,-1]]
What about this?
>>> first_element, last_element = some_list[0], some_list[-1]
This isn't a "slice", but it is a general solution that doesn't use explicit indexing, and works for the scenario where the sequence in question is anonymous (so you can create and "slice" on the same line, without creating twice and indexing twice): operator.itemgetter
import operator
# Done once and reused
first_and_last = operator.itemgetter(0, -1)
...
first, last = first_and_last(some_list)
You could just inline it as (after from operator import itemgetter
for brevity at time of use):
first, last = itemgetter(0, -1)(some_list)
but if you'll be reusing the getter a lot, you can save the work of recreating it (and give it a useful, self-documenting name) by creating it once ahead of time.
Thus, for your specific use case, you can replace:
x, y = a.split("-")[0], a.split("-")[-1]
with:
x, y = itemgetter(0, -1)(a.split("-"))
and split
only once without storing the complete list
in a persistent name for len
checking or double-indexing or the like.
Note that itemgetter
for multiple items returns a tuple
, not a list
, so if you're not just unpacking it to specific names, and need a true list
, you'd have to wrap the call in the list
constructor.
Just thought I'd show how to do this with numpy's fancy indexing:
>>> import numpy
>>> some_list = ['1', 'B', '3', 'D', '5', 'F']
>>> numpy.array(some_list)[[0,-1]]
array(['1', 'F'],
dtype='|S1')
Note that it also supports arbitrary index locations, which the [::len(some_list)-1]
method would not work for:
>>> numpy.array(some_list)[[0,2,-1]]
array(['1', '3', 'F'],
dtype='|S1')
As DSM points out, you can do something similar with itemgetter:
>>> import operator
>>> operator.itemgetter(0, 2, -1)(some_list)
('1', '3', 'F')