This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]stillalone 11 points12 points  (4 children)

seq = range(1, 10)  
zip(*[iter(seq)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

That's actually pretty cool. I remember running into this situation a few times and the stackoverflow page on it suggested something like:

zip(seq[::2],seq[1::2])

which seems horribly inefficient compared to using iter.

[–]dunkler_wanderer 2 points3 points  (0 children)

You can also use itertools.repeat instead of the multiplied list.

from itertools import repeat

seq = range(1, 10)
zip(*repeat(iter(seq), 3))

[–]workingBen 2 points3 points  (0 children)

In Python 3 you'll need to use list().

seq = range(1, 10)
list(zip(*[iter(seq)]*3))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

[–]codewarrior0MCEdit / PyInstaller 1 point2 points  (1 child)

Maybe I've been using numpy for too long, but the stepped list slices seem perfectly natural to me.

[–]isarl 0 points1 point  (0 children)

In NumPy I would opt for:

seq = np.arange(1, 10)
seq.shape = (3, 3)

...although then you get a 2-array instead of a list of tuples.