A list comprehension to do this?...

David Eppstein eppstein at ics.uci.edu
Wed Sep 18 17:27:24 EDT 2002


In article <3D88E4F5.B443918 at quartercase.com>,
 joe sixpack <joe.sixpack at quartercase.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...

It's not much different, but it can easily be done with a list comp:

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

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list