1

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'')] 
1
  • 2
    Actually you don't have a list of lists, you have a list of tuples Commented Nov 13, 2013 at 3:03

2 Answers 2

4

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] 
Sign up to request clarification or add additional context in comments.

3 Comments

awesome! thank you. i knew it was simpler than what i had been trying!
Why not just data = [x[:-2] for x in data]?
@iCodez, done. I wrote it out in 2 steps for the sake of elaboration but I guess it just makes me look like a dummy ;-)
2

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.

2 Comments

just curious on the indicators or how i was supposed to know that i had a list of tuples as opposed to a list of a list??
@Barnaby, [1,2,3] is a list. (1,2,3) is a tuple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.