Hi forum,
I have trouble understanding this n-length groups idiom
>>> s = [1, 2, 3, 4, 5, 6]
>>> list( zip( *[ iter( s ) ] *2 ) )
[(1, 2), (3, 4), (5, 6)]
>>>
Could you please teach me. Thanks in advance.
Does the whole expression evaluate in this order?
Step 1: iter(s)
It’s a iterator on a sequence.
Step 2: [ iter(s) ] *2
It’s a list repetition. Two iterators on the sequence. Take two value from the sequence one time. There’re two stream of iterator:
s1: [1, 3, 5]
s2: [2, 4, 6]
Step 3: *[ iter(s) ] *2
I do not understand the first * star operator. Is it unzip or unpack operator? Or are unzip and unpack the same thing? What does it do here?
Step 4: zip( *[ iter(s) ] *2)
s1: [1, 3, 5]
s2: [2, 4, 6]
So it’s equal to:
zip(s1, s2)
(1, 2), (3, 4), (5, 6)
Step 5: list( zip( * [ iter(s) ] *2 ) )
Constructs a list to show the zip result
[(1, 2), (3, 4), (5, 6)]