How to remove the first and last item in a list?

I have a list

['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 '] 

How to remove the first element Qand 0002, the last element?

+5
source share
2 answers

I'm not sure exactly what you want, as it is unclear, but this should help. You actually only have one item on this list.

Assuming all your list items are strings with spaces as separators, here's how you can remove the first and last group of characters from each line in the list.

>>> L = ['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 ']
>>> [' '.join(el.split()[1:-1]) for el in L]
['0006 005C 0078 0030 0030 0033 0034 ONE_OF']
+11
source

If your list is stored in my_list, then this should work.

my_list = my_list[1:-1]
+40
source

All Articles