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

2006-12-01 Thread Peter Otten
Peter Otten wrote: > Here is another implementation that cuts maximum memory down from 100 to > 50%. > > from itertools import islice > def swap(items): > items[::2], items[1::2] = islice(items, 1, None, 2), items[::2] > return items Unfortunately, the following >>> a = [1, 2, 3] >>> a[

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

2006-12-01 Thread Peter Otten
Steven D'Aprano wrote: > On Thu, 30 Nov 2006 11:17:17 +0100, Peter Otten wrote: > >> Steven D'Aprano wrote: >> >>> And remember that if alist is truly huge, you may take a performance hit >>> due to duplicating all those megabytes of data when you slice it. >> >> Having the same object in two l

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

2006-11-30 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> 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

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

2006-11-30 Thread Steven D'Aprano
On Thu, 30 Nov 2006 11:17:17 +0100, Peter Otten wrote: > Steven D'Aprano wrote: > >> And remember that if alist is truly huge, you may take a performance hit >> due to duplicating all those megabytes of data when you slice it. > > Having the same object in two lists simultaneously does not doub

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

2006-11-30 Thread Peter Otten
Duncan Booth wrote: > items[::2], items[1::2] = items[1::2], items[::2] Cool. I really should have found that myself. Peter -- http://mail.python.org/mailman/listinfo/python-list

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

2006-11-30 Thread Duncan Booth
Peter Otten <[EMAIL PROTECTED]> 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 differ