Is there a list comprehension to do this?

Christophe Delord christophe.delord at free.fr
Wed Sep 18 23:21:01 CEST 2002


This solution is just the same as yours. The same loop, with the same
expression (xx[i+1],xx[i]) but using list comprehension.

>>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> [ (xx[i+1], xx[i]) for i in range(0,len(xx),2) ]
[(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)]
>>>

On Wed, 18 Sep 2002 20:45:58 GMT
"Joe Sixpack" <joe.sixpack at whoopie.com> 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)]
> >>>
> 
> Thanks in advance...
> 
> 


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list