Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does Python interpret a half 'empty' tuple (x,)?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading