Slicing versus loops, was Re: for i in range() anti-pattern

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 30 05:42:03 EST 2006


Peter Otten <__peter__ at web.de> wrote:

> That example was chosen to prove your point. The real contender for the
> "swap items" problem are slices. 
> 
> def swap_slice(items):
>     left = items[::2]
>     items[::2] = items[1::2]
>     items[1::2] = left
>     return items
> 

It makes no difference to the time or memory use, but you can of course 
also write swap_slice using the aforementioned 'well known idiom':

items[::2], items[1::2] = items[1::2], items[::2]




More information about the Python-list mailing list