tags:

views:

60

answers:

3

From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large lists of lists)?

+1  A: 

Use list comprehension.

 newlist = [x[:2] for x in mylist]
KennyTM
+5  A: 

The easiest way is probably to use a list comprehension:

newlist = [sublist[:2] for sublist in mylist]
sth
+3  A: 

Quick answer:

first_two = [sublist[:2] for sublist in mylist]

If having a list of tuples is ok, then a faster answer (2x by my measurements):

import operator
map(operator.itemgetter(0, 1), mylist)

Measurements:

t = timeit.Timer("[i[:2] for i in ll]", "ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t.timeit(10000)
>>> 2.2732808589935303

t2 = timeit.Timer("map(operator.itemgetter(0, 1), ll)", "import operator; ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t2.timeit(10000)
>>> 1.3041009902954102
Robert Kluin