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

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 30 14:09:11 CET 2006


Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote:

> Everybody always forgets corner cases... like lists with odd number of
> items... *wink*
> 
I didn't forget. I just assumed that raising an exception was a more useful 
response.

> Here is a version that handles both odd and even length lists:
> 
> def swap_slice(items):
>     left = items[:len(items)-1:2]
>     items[:len(items)-1:2] = items[1::2]
>     items[1::2] = left
>     return items
> 
I guess a viable alternative to raising an exception would be to pad the 
list to even length:

[1, 2, 3] -> [2, 1, Padding, 3]

for some value of Padding. I don't think I would expect swap_slice to 
silently fail to swap the last element.



More information about the Python-list mailing list