I came across this code fragment and can’t understand what is happening here.
X = np.linspace(-5,5,50)
Y = np.linspace(-5,5,50)
X, Y = np.meshgrid(X,Y)
pos = np.empty(X.shape+(2,))
Why is (2,) necessary here and how does Python interpret half empty tuples like that in general?
>Solution :
(2,) is literal for tuple with one element. You need that in
pos = np.empty(X.shape+(2,))
as X.shape is tuple and + denotes concatenating tuples in python, in this particular example you are adding another dimension before using numpy.empty.
Tuples and Sequence docs put it following way
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these. Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma (it is not
sufficient to enclose a single value in parentheses). Ugly, but
effective.