3

I'm a newbie with python and I don't understand why doesn't the following work:

ea = zip([[200, 1], [10, 1]])

since I'm getting

[([200, 1],), ([10, 1],)]

while I should add an asterisk like

ea = zip(*[[200, 1], [10, 1]])

to obtain the result I want, i.e.

[(200, 10), (1, 1)]

I thought * was meant to convert the list to a tuple, what am I getting wrong?

Dean
  • 6,610
  • 6
  • 40
  • 90

2 Answers2

8

If you have time you can read this post, it's good resource to understand how * works in Python.

The asterisk in Python unpacks arguments for a function call, please refer to here

z = [4, 5, 6]
f(*z)

will be same as:

f(4,5,6)

** in dictionary does similar work as * in list.

tfl
  • 3
  • 4
Andreas Hsieh
  • 2,080
  • 1
  • 10
  • 8
3

zip expects multiple arguments, like this:

>>> zip([200, 1], [10, 1])
[(200, 10), (1, 1)]

If you want to use only one argument, then use the * because it has the effect of breaking it up into multiple arguments:

>>> zip(*[[200, 1], [10, 1]])
[(200, 10), (1, 1)]
>>> 

The * does not convert lists to tuples. It unpacks lists (documentation).

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks, is this the same behavior for asterisk I read here: http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters ?? – Dean May 26 '16 at 00:02
  • That question talks about _defining_ functions with `*` and `**`. Your question is about using an _existing_ function. So, it is analogous but not the same. – John1024 May 26 '16 at 00:08