If you had a general grouper
function, this would be trivial:
print ' '.join(grouper(num, 5))
And it's easy to write that function. In fact, there are two different ways to do it.
Slicing—as in inspectorG4dget's answer—only works on sequences, and gives you an incomplete group if there's part of a group left at the end. If that fits your requirements—and for your question, it does—it's definitely simpler, and a little faster.
Here's a general-purpose grouper:
def grouper(sequence, n):
return (sequence[i:i+n] for i in xrange(0, len(sequence), n))
Iterator grouping is more complicated, but it works on any iterable, even one-shot iterators, and is easy to customize for any of the three reasonable behaviors for trailing values.
You can find a recipe in the itertools
docs, but here's a slightly shorter version (which truncates a partial group at the end):
def grouper(iterable, n):
return zip(*[iter(iterable)]*n)
Or, if you install the more_itertools
library, you can just import
an implementation from there.
How grouper works explains how this implementation works.