swapping numeric items in a list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Aug 22 21:38:43 EDT 2006


Jiang Nutao:
> To convert list
>     aa = [0x12, 0x34, 0x56, 0x78]
> into
>     [0x34, 0x12, 0x78, 0x56]
> How to do it fast? My real list is huge.

Note that:

>>> a = range(6)
>>> a
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[1::2]
[1, 3, 5]

So you can do:

>>> a[::2], a[1::2] = a[1::2], a[::2]
>>> a
[1, 0, 3, 2, 5, 4]

Bye,
bearophile




More information about the Python-list mailing list