How to remove the last item in each tuple in a list

I have a list like:

alist = [[a,b,(1,2)], [a,b,(1,2)], [a,b,(1,2)]]

I want to remove the last item from all items in the list. Thus, the result will be:

alist = [[a,b], [a,b], [a,b]]

Is there a quick way to do this?

+3
source share
2 answers

You can use the list view to create a new list that removes the last item.

>>> 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 to increase efficiency, you can change 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]]
+9
source

This is the core stuff of Python. You should be able to do this after reading the Python tutorial.

>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> for li in alist:
...     print li[0:2]
...
[1, 2]
[5, 6]
[9, 10]
>>>

Later you can move on to intermediate materials such as list comprehension, etc.

0
source

Source: https://habr.com/ru/post/1771077/


All Articles