Small doubt in the base code (W1 A3 Exercise 4)

Hello everyone, I hope you are doing well.
I’m finalizing A3 from W1 and a doubt arose.
Why do we use an underscore in this part of the code?

why do we use it parameters_values, _ =
and not that parameters_values =

I apologize if the question is too basic.
Thanks!

The 2nd value returned by dictionary_to_vector is ignored. _ is used in python to hint that the author wants to ignore this value. Please read up on unpacking in python to know how multiple values can be assigned simultaneously.

1 Like

Yes, this is a standard python syntax that says you don’t care about that return value. You could also assign it to a variable that you never use, but that takes up memory for no purpose. Note that if you have a function that returns multiple values, python is not like other languages (e.g. MATLAB): if you just specify one return value, python “does you a favor” and packs all the return values into a single “tuple” and assigns that to your single LHS value. That’s not what you want and will make a mess in this case. Of course you can make it work, if you know what to expect, but using the _ syntax is a lot cleaner.

Actually the better way to describe what I said in the first paragraph there is that a python function that returns multiple values actually returns them as a tuple and what is happening on the LHS of the assignment statement there is the “unpacking” of a tuple as Balaji says and the _ syntax is a way to say that you don’t care about that element of the unpacked tuple.

1 Like