1

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
  • 5,852
  • 3
  • 32
  • 78

2 Answers2

4

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
  • 1,800
  • 1
  • 9
  • 8
1

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
  • 103,964
  • 12
  • 124
  • 155
  • 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