Reading 3 objects at a time from list

Aahz aahz at pythoncraft.com
Sat Apr 11 19:42:00 CEST 2009


In article <49e06774$0$700$5fc30a8 at news.tiscali.it>,
Francesco Bochicchio  <bockman at virgilio.it> wrote:
>> On Sat, Apr 11, 2009 at 1:44 AM, Matteo <tadwelessar at gmail.com> wrote:
>>>
>>> I need to pass the numbers to a function, but three at a time, until
>>> the string ends. The strings are of variable length, but always a
>>> multiple of three.
>
>I would do that with a generator:
>
> >>> def groups(l,n) :
>...   while l: yield l[:n]; l=l[n:]
>...

Unfortunately, that's O(N**2) albeit with an extremely small constant
factor, because popping off the head of the list requires a full list
copy.  You're probably okay with this algorithm unless the string could
be megabytes.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?



More information about the Python-list mailing list