views:

92

answers:

2

Hey, I've got a list like

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

I want to remove the third element from all the elements in alist, or it means the last one in the elements of a list

So the result will be

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

Do we have any fast way to do this? Thanks!

Your script works in python shell, but does not work in my program, don't know why is that

happens.

I done the reading of Python quick book, heh~

rows = [[1,2,(1,2)],[1,2,(1,2)],[1,2,(1,2)]]
print rows
rows = [x[:-1] for x in rows] 
print rows
+7  A: 

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]]
KennyTM
Beat me by 15 seconds. I shouldn't have wasted time wondering why the person isn't using a good Python tutorial.
S.Lott
I felt the urge to remove some clutter. Your first answer was approximately perfect. The detailed example might be more helpful, but, I think it's clearer with two fewer lines of distraction from that essential, crystal clear line of code.
S.Lott
"if you want efficiency"? How is this more efficient? Do you have some numbers to support this claim?
S.Lott
@S.Lott: Sure http://www.ideone.com/4JajX. In fact, it is quite clear that the 1st version is slower because the whole list is copied.
KennyTM
@KennyTM: Excellent!
S.Lott
A: 

This is basic Python stuff. You should be able to do it 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 on, you can go to intermediate stuff like list comprehension etc

ghostdog74