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)?
views:
60answers:
3
+5
A:
The easiest way is probably to use a list comprehension:
newlist = [sublist[:2] for sublist in mylist]
sth
2010-10-29 15:55:54
+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
2010-10-29 16:15:20