Reputation: 12539
I have the data below, which is a list of lists. I would like to remove the last two elements from each list, leaving only the first three elements. I have tried list.append()
, list.pop()
but can't seem to get them to work. I guess it is not possible to remove elements from a list in a for loop, which is what I had been previously trying. What is the best way to go about this?
data = [(datetime.datetime(2013, 11, 12, 19, 24, 50), u'78:E4:00:0C:50:DF', u' 8', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 50), u'78:E4:00:0C:50:DF', u' 8', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 48), u'9C:2A:70:69:81:42', u' 5', u'Hon Hai Precision In 12:', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'00:1E:4C:03:C0:66', u' 9', u'Hon Hai Precision In', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'20:C9:D0:C6:8F:15', u' 8', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:5D:43:90:C8:0B', u' 11', u'Intel Orate', u' MADEGOODS'), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:96:7B:C1:76:90', u' 15', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'68:96:7B:C1:76:90', u' 15', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'04:F7:E4:A0:E1:F8', u' 32', u'Apple', u''), (datetime.datetime(2013, 11, 12, 19, 24, 47), u'04:F7:E4:A0:E1:F8', u' 32', u'Apple', u'')]
Upvotes: 1
Views: 136
Reputation: 304463
As @christian says, you have a list of tuple
, as opposed to list
. The distinction is significant here as tuple
is immutable. You can convert to list
of list
like this
data = map(list, data)
Now you can mutate each item as you iterate over it
for item in data:
del item[-2:]
In your case the list comprehension is better because it works on your list
of tuple
equally well.
Upvotes: 2
Reputation: 23394
You could use a list comprehension and create a new list of lists with 2 elements removed from each sublist
data = [x[:-2] for x in data]
Upvotes: 4