+ 2

zip() and '*' before variable - what do they do?

Hi, there's a Python code: *x,y = [1,2], [3,4], [5,6], print(list(zip(*x + [y]))[1][1]) Can someone explain me please usage of '*' before x variable and zip() function? It's really confusing.

1st Jun 2018, 8:54 AM
Pav
2 Réponses
+ 5
'*' is a so-called greedy operator. It means it takes as much as it is allowed. In your sample *x,y = [1,2], [3,4], [5,6], the 'y' variable is the last, so it takes the last value from the values' set ([5, 6]), then "greedy" *x takes all the rest ([1,2], [3,4]). >>> *x, y = 1,2,3,4 >>> x [1, 2, 3] >>> y 4 >>> x, *y = 1,2,3,4 >>> x 1 >>> y [2, 3, 4] >>> >>> x, *y, z = 1,2,3,4 >>> x 1 >>> y [2, 3] >>> z 4 >>> and so on. zip in general takes several sequences as an input and returnes a special tuple where first element is firstl emelents of the input sequences: >>> s = 'abc' >>> t = (10, 20, 30) >>> u = (-5, -10, -15) >>> list(zip(s,t,u)) [('a', 10, -5), ('b', 20, -10), ('c', 30, -15)] >>> Note the list method called to represent zip tuple in a proper way.
1st Jun 2018, 1:50 PM
strawdog
strawdog - avatar
+ 1
strawdog man, that's the best explanation I've ever received! Really simple to understand, thank you!
1st Jun 2018, 11:13 PM
Pav