0

While exploring color codes in the Matplotlib Library of Python, I came across this piece of code:

x,y,c=zip(*np.random.rand(30,3))

I looked up the working of the built in function zip() in Python, but I do not seem to undertstand the role of * before the numpy random statement. Thanks in advance.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Nisha
  • 33
  • 7
  • 2
    Can you please link to this code (file and line number)? I'd like to fix it. – Mad Physicist Aug 10 '20 at 02:35
  • This has been closed with the wrong dup. This question is not about asterisks in the paremeter list of a function, it is about iterable unpacking a la PEP448. A better dup is: https://stackoverflow.com/questions/36980992/asterisk-in-tuple-list-and-set-definitions-double-asterisk-in-dict-definition – Craig Aug 10 '20 at 02:39
  • 1
    @Craig. Added to the list – Mad Physicist Aug 10 '20 at 03:39

1 Answers1

1

It is a very weird way to transpose. Same can be achieved with:

x,y,c=np.random.rand(3, 30)  # or, np.random.rand(30, 3).T

How it works: say, we have an 3x2 array data = [[1,2], [3,4], [5,6]]. To transpose it without numpy and get a 2x3 array [[1,3,5], [2,4,6]] we can do:

data_transposed = list(zip(*data))

This is equivalent to:

data_transposed = list(zip([1,2], [3,4], [5,6]))

zip will produce an iterator of , , ... etc. - which will result in a list of: , , ... - i.e., a transpose of data

Marat
  • 15,215
  • 2
  • 39
  • 48