How to not recognize the code using izip_longest to arrange the list?

The best answer in What is the most "pythonic" way to iterate over a list in pieces? using the izip_longest function to sort the list. But I can’t understand this.

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

for item in grouper(range(10), 4):
    print list(item)

I run the code above, then ordered lists are created:

[1 ,2, 3, 4]
[5, 6, 7, 8]
[9, 10, None, None]

I tried to follow it step by step:

In [1]: args = [iter(range(10))] * 4

In [2]: args
Out[2]: 
[<listiterator at 0x1ad7610>,
 <listiterator at 0x1ad7610>,
 <listiterator at 0x1ad7610>,
 <listiterator at 0x1ad7610>]

The list is created by the same iterator. I know that the izip_longest function is implemented to create pairs of lists. How does an iterator translate into izip_longest ordered lists? Thank.

+4
source share
1 answer

grouper . [iter(iterable)] * n n . ; , . :

>>> x = [1, 2, 3]
>>> a, b = [iter(x)] * 2
>>> next(a)
1
>>> next(b)
2

izip_longest, , zip, . args, . , , . , izip_longest , , . ; , , , , , .

+6

All Articles