I've got a list like:
alist = [[a,b,(1,2)], [a,b,(1,2)], [a,b,(1,2)]]
I want to remove the last element from all the elements in a list. So the result will be:
alist = [[a,b], [a,b], [a,b]]
Is there a fast way to do this?
You could use list comprehension to create a new list that removes the last element.
>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> [x[:-1] for x in alist] # <-------------
[[1, 2], [5, 6], [9, 10]]
However, if you want efficiency you could modify the list in-place:
>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> for x in alist: del x[-1] # <-------------
...
>>> alist
[[1, 2], [5, 6], [9, 10]]
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