Is there a list comprehension to do this?

Alex Martelli aleax at aleax.it
Wed Sep 18 17:02:32 EDT 2002


Joe Sixpack wrote:

> Is there a list comprehension or other 'cleaner' or 'prettier' way
> to do the following:
> 
>>>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>>> ww = []
>>>> for i in range(0, len(xx), 2):
>  ww.append((xx[i+1],xx[i]))
> 
>>>> ww
> [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)]

Sure, you can always use a list comprehension in lieu of a loop
that builds a list by calling .append -- a mechanical transcription:

ww = [(xx[i+1],xx[x]) for i in range(0, len(xx), 2)]

In Python 2.3, where lists finally support generalized slicing:

ww = zip(xx[1::2],x[::2])

but that doesn't work in 2.2 and earlier, alas.


Alex




More information about the Python-list mailing list