Question
Asked By – Oliver Zheng
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 look like if it was written with more verbose code?
Now we will see solution for issue: How does zip(*[iter(s)]*n) work in Python?
Answer
iter()
is an iterator over a sequence. [x] * n
produces a list containing n
quantity of x
, i.e. a list of length n
, where each element is x
. *arg
unpacks a sequence into arguments for a function call. Therefore you’re passing the same iterator 3 times to zip()
, and it pulls an item from the iterator each time.
x = iter([1,2,3,4,5,6,7,8,9])
print zip(x, x, x)
This question is answered By – Ignacio Vazquez-Abrams
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0