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\',
One way:
some_list[::len(some_list)-1]
A better way (Doesn't use slicing, but is easier to read):
[some_list[0], some_list[-1]]
You can do it like this:
some_list[0::len(some_list)-1]
These are all interesting but what if you have a version number and you don't know the size of any one segment in string from and you want to drop the last segment. Something like 20.0.1.300 and I want to end up with 20.0.1 without the 300 on the end. I have this so far:
str('20.0.1.300'.split('.')[:3])
which returns in list form as:
['20', '0', '1']
How do I get it back to into a single string separated by periods
20.0.1
Fun new approach to "one-lining" the case of an anonymously split
thing such that you don't split it twice, but do all the work in one line is using the walrus operator, :=, to perform assignment as an expression, allowing both:
first, last = (split_str := a.split("-"))[0], split_str[-1]
and:
first, last = (split_str := a.split("-"))[::len(split_str)-1]
Mind you, in both cases it's essentially exactly equivalent to doing on one line:
split_str = a.split("-")
then following up with one of:
first, last = split_str[0], split_str[-1]
first, last = split_str[::len(split_str)-1]
including the fact that split_str
persists beyond the line it was used and accessed on. It's just technically meeting the requirements of one-lining, while being fairly ugly. I'd never recommend it over unpacking or itemgetter solutions, even if one-lining was mandatory (ruling out the non-walrus versions that explicitly index or slice a named variable and must refer to said named variable twice).
Another python3 solution uses tuple unpacking with the "*" character:
first, *_, last = range(1, 10)
Utilize the packing/unpacking operator to pack the middle of the list into a single variable:
>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *middle, last = l
>>> first
'1'
>>> middle
['B', '3', 'D', '5']
>>> last
'F'
>>>
Or, if you want to discard the middle:
>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *_, last = l
>>> first
'1'
>>> last
'F'
>>>