Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last element in each list in a list

Tags:

python

list

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?

like image 680
user483144 Avatar asked Jan 22 '23 05:01

user483144


1 Answers

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]]
like image 165
kennytm Avatar answered Jan 29 '23 00:01

kennytm