[Tutor] Rearrange a list
Peter Otten
__peter__ at web.de
Fri May 1 07:44:07 EDT 2020
EK Esawi via Tutor wrote:
> Hi All--,
>
> 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. I am
> not concerned about the 1st item on the list. I am hoping that this can be
> done vis list comprehension or something like it w/o using other Python
> modules.
>
> Here is my attempt but the resulting pairing is wrong. It contains
> unwanted pairs such as [4,6] and [8,10]
>
>
> X= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>
> b=[[i, i + 2] for i in range(1,len(x) - 1)]
>
> b=[[1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10]]
>
> again, I am not concerned with the 1st sublist
How about
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x[3::4], x[2::4] = x[2::4], x[3::4]
>>> x
[1, 2, 4, 3, 5, 6, 8, 7, 9, 10]
?
More information about the Tutor
mailing list