Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    i = iter(array)
    return zip(i, i, i)

There you go. All but neceessary magic gone with just one line more.


A much clearer solution, I would also add a comment reminding people how zip works.


Really? What's the point in explaining a standard language function that they should know, and can just Google if they don't remember?


It's using a somewhat-obscure guarantee that doesn't come up in normal usage of the function - namely, that it will always get the iterator values in left-right order.


it depends on the kind of code you write. i guess if you're writing web server stuff, documenting this makes sense. but in maths-related code, it's pretty standard. you use something very similar to transpose matrices, for example.

(and the original article is dealing with coords in graphics, which is "maths-related code" in my book, but perhaps not in everyone's)


The original source is taken from a medical image DICOM viewer. In my limited experience as a medical physics student, the people working with these tools would really benefit from a comment explaining the code. They are most definitely not coders, most of them having barely done anything more than write a few matlab scripts.


This is hardly a typical environment. All code would be challenging, even commented code. Excessive commenting would be necessary: write the program again in English.


Yeah, I was thinking the same thing. The only downside is that it isn't generic for variable length chunks.


It is clearer, but uses a fixed number of arguments, so may be unsuitable for some applications.


The current function has the same restriction. In their case it's in the form of " * 3 ".


That `3` can be trivially replaced with a variable in a way that `(i, i, i)` cannot. But still, the refactoring of the iterator into a separate variable is the key step which reinforces that the same object is being passed 3 times


You don't have to use the same function to solve every problem.


If you only ever need to chunk a list into 3-tuples, sure. If you want a general solution for chunking a list with zip and an iterator, this solution doesn't scale (look at hartror's and bjourne's posts for something that does).


I think that dependency on argument evaluation order inside zip function smells a bit.

It's OK here, but may bite you with a different function.


    The left-to-right evaluation order of the
    iterables is guaranteed.
http://docs.python.org/2/library/functions.html#zip


Yes, but only for zip, which I believe was the parent posters point. With another function this technique might not work.


That is infinitely more readable.


Much, much better.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: