[Tutor] Rearrange a list

Alan Gauld alan.gauld at yahoo.co.uk
Fri May 1 09:47:45 EDT 2020


On 01/05/2020 09:38, EK Esawi via Tutor wrote:

> I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,……]. I want to rearrange the order of the positions 
> of the list values as follow [1,2,4,3,5,6,8,7,9,10,12,13,15……]. 

> Or something like this  [1,[2,4],[3,5],[6,8],[7,9],[10,12],……] which then can be flattened. 


Here's one method:

>>> odds = range(3,50,2)
>>> evens = range(2,50,2)
>>> [1] + [list(odds[n-1:n+1]) if n%2 else list(evens[n:n+2])
            for n in range(0,20)]
[1, [2, 4], [3, 5], [6, 8], [7, 9], [10, 12], [11, 13], [14, 16], [15,
17], [18, 20], [19, 21], [22, 24], [23, 25], [26, 28], [27, 29], [30,
32], [31, 33], [34, 36], [35, 37], [38, 40], [39, 41]]



HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list