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?
Explanation: The function pop removes the first element when used on a set and the last element when used to a list.
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.
If your list is stored under my_list
then this should work.
my_list = my_list[1:-1]
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']
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With