I understood simple concepts about comma operator in python. For instance,
x0, sigma = 0, 0.1
means x0=0, and sigma=0.1. But I obtained a code that has a line that looks like the following.
y, xe = np.histogram(np.random.normal(x0, sigma, 1000))
where the output of y and xe are the followings.
y
Out[10]: array([ 3, 17, 58, 136, 216, 258, 189, 87, 31, 5], dtype=int64)
xe
Out[11]:
array([-0.33771565, -0.27400243, -0.21028922, -0.146576 , -0.08286279,
-0.01914957, 0.04456364, 0.10827686, 0.17199007, 0.23570329,
0.2994165 ])
I am not sure how to read y, xe expression. What could I look up to understand what it's saying?
x0, sigma = 0, 0.1
is syntactic sugar. Some stuff is happening behind the scenes:0, 0.1
implicitly creates a tuple of two elements.x0, sigma =
unpacks that tuple into those two variables.If you look at the docs for
numpy.histogram
, you see that it returns these two things:Your
y, xe = ...
unpacks the tuple of the two returned arrays respectively. That is why youry
is assigned to a numpy int64 array and yourxe
assigned to a numpy float array.A comma forms a tuple, which in Python looks just like an immutable list.
Python does destructuring assignment, found in a few other languages, e.g. modern JavaScript. In short, a single assignment can map several left-hand variables to the same number of right-hand values:
This is equivalent to
foo = 1
andbar = 2
done in one go. This can be used to swap values:You can use a tuple or a list on the right side, and it will be unpacked (destructured) the same way if the length matches:
You can return a tuple or a list from a function, and destructure the result right away:
I hope this answers your question. The histogram function returns a 2-tuple which is unpacked.
This might be a solution for you: