im facing this question, and I was hoping some of you might help out:
Write a function that accepts an iterable and a positive number n. The function returns a new iterator that gives values from the original in tuples of length n. Pad missing values with 'None' if needed for the very last tuple.
for example:
for x in bunch_together(range(10),3): print(x)
return values are
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)
This is what I come up with so far:
def bunch_together(iterable,n):
tup = tuple()
for item in iterable:
for i in range(n):
tup += (i,)
yield tup
but this obviously doesn't work because I didnt accounted for the range at all(the output as of now looks something like this:
(0, 1, 2)
(0, 1, 2, 0, 1, 2)
(0, 1, 2, 0, 1, 2, 0, 1, 2)
...#(goes on)
I could either create a generator of build an iterator (as in building a class composed of init iter and next) Thanks for the help!