Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have the List

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

How do I remove the first element, Q and 0002, the last element?

like image 738
Python Avatar asked Jul 05 '12 05:07

Python


People also ask

Which function removes a set first and the last element from a list?

Explanation: The function pop removes the first element when used on a set and the last element when used to a list.

How do I remove the last two elements from a list in Python?

Using del Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.


3 Answers

If your list is stored under my_list then this should work.

my_list = my_list[1:-1]
like image 146
Jakob Bowyer Avatar answered Dec 05 '22 14:12

Jakob Bowyer


I'm not sure exactly what you want since it is unclear but this should help. You actually only have a single element in that list.

Assuming all your list items are strings with spaces as delimiters, here is how you can remove the first and last group of characters from each string 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']
like image 44
jamylak Avatar answered Dec 05 '22 14:12

jamylak


Another (quite Pythonic) way to do it is using the extended sequence unpacking feature:

my_list = _ , *my_list, _

Example

>>> my_list =  [1, 2, 3, 4, 5]
>>> _, *my_list, _ = my_list
>>> my_list
[2, 3, 4]
like image 37
Giorgos Myrianthous Avatar answered Dec 05 '22 13:12

Giorgos Myrianthous