s = [1,2,3,4,5,6,7,8,9]
n = 3
zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)]
How does zip(*[iter(s)]*n)
work? What would it l
It is probably easier to see what is happening in python interpreter or ipython
with n = 2
:
In [35]: [iter("ABCDEFGH")]*2
Out[35]: [, ]
So, we have a list of two iterators which are pointing to the same iterator object. Remember that iter
on a object returns an iterator object and in this scenario, it is the same iterator twice due to the *2
python syntactic sugar. Iterators also run only once.
Further, zip takes any number of iterables (sequences are iterables) and creates tuple from i'th element of each of the input sequences. Since both iterators are identical in our case, zip moves the same iterator twice for each 2-element tuple of output.
In [41]: help(zip)
Help on built-in function zip in module __builtin__:
zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
The unpacking (*) operator ensures that the iterators run to exhaustion which in this case is until there is not enough input to create a 2-element tuple.
This can be extended to any value of n
and zip(*[iter(s)]*n)
works as described.