tags:

views:

86

answers:

2

I've got a python list

alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,999] ]

I need the result is

alist = [[0,4,8,13], [3, 4, 8, 999]]

It means first two and last two numbers in each alist element.

I need a fast way to do this as the list could be huge.

+11  A: 
[x[0][:2] + x[-1][-2:] for x in alist]
Ignacio Vazquez-Abrams
+1  A: 

The object is actually a tuple, rather than a list. This can trip you up if you're expecting it to be mutable and it's hard to read. Consider using the continuation character \ for long lines:

alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]

is clearer as

alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], \
        [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]

which also helps you spot the double bracket that makes this a tuple. For a list:

alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13], \
        [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]]

If list comprehension as suggested in Javier's answer doesn't meet your speed requirement, consider a numpy array.

Richard Careaga