-1

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?

lpnorm
  • 459
  • 3
  • 10
  • 1
    That's how you write a tuple with one element. – khelwood Nov 22 '21 at 10:45
  • 1
    The point is that (2) == 2 i.e., (2) is not a tuple. Thus a tuple with only one element needs a "special" syntax namely (2,) –  Nov 22 '21 at 10:46
  • 1
    _half empty tuple_ is interesting term. What would be _full tuple_? – buran Nov 22 '21 at 10:49
  • So is that the same as (2, None)? A full tuple to me is one where each component is determined. Is this part of pythons lazy evaluation or something? – lpnorm Nov 22 '21 at 10:50
  • 1
    `(2, None)` is a tuple with two elements, `2` and `None`. `(2,)` is a tuple with one element. Note that the parentheses are needed in your expression but in an assignment you could write e.g. `a = 2,` – Passerby Nov 22 '21 at 10:51
  • ``(2,)`` is no more a "half empty tuple" than ``(2, 3,)`` is a "one third empty triple". – MisterMiyagi Nov 22 '21 at 10:54
  • @MisterMiyagi I was just confused how python deals with this. It seemed to me like e.g. a function that lacks an argument. – lpnorm Nov 22 '21 at 11:01

2 Answers2

2

(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.

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • So the resulting matrix is 50x50x2? I.e. if one used ```pos = np.empty(X.shape+(50,))``` one would get a cubic matrix of 50x50x50? – lpnorm Nov 22 '21 at 10:58
  • 1
    @lpnorm yes, you will get 50x50x2 array with given code and 50x50x50 if you replace `(2,)` using `(50,)` – Daweo Nov 22 '21 at 11:04
1

According to the python language reference here:

A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions).

Since (2) is an integer, you need to somehow inform the interpreter that what you mean is actually a tuple with a single item and you do that by adding the comma at the end.

you can test this by running this on the interpreter:

>>> type((2))
<class 'int'>
>>> type((2,))
<class 'tuple'>