1

I've seen both zeros(5) vs zeros((5,)) to initialize a variable in python, where n is an integer. When I print both variables using print() function, I get [ 0. 0. 0. 0. 0.] for both options. Why would one use the second option, which seems way more complicated?

Ali Camilletti
  • 116
  • 1
  • 3
  • 11
thylakoid12
  • 137
  • 1
  • 9
  • `zeros((x))`, `zeros((x, y))`, `zeros((x, y, z))`... See the pattern? – Ignacio Vazquez-Abrams Oct 02 '17 at 17:57
  • yes, thanks! But why would one use `zeros((x))` if `zeros(x)` leads to the same result? Is there a difference in dimension or the way the variable is stored? And what is the difference between `zeros((5,))` and `zeros((5))`? Thanks! – thylakoid12 Oct 02 '17 at 19:06

1 Answers1

1

Taking Numpy as the example, from numpy.ma.zeros doc:

numpy.ma.zeros(shape, dtype=float, order='C') = <numpy.ma.core._convert2ma instance>

Return a new array of given shape and type, filled with zeros.

Parameters:

shape : int or sequence of ints

Shape of the new array, e.g., (2, 3) or 2.

...

So both np.zeros(5) and np.zeros((5,)) are ok and you got the same results, but you passed with different types of parameters: the first is int, the second is tuple of ints, which is also valid since it is a sequence of ints. To construct a tuple of one int element, you need to add an extra comma (see this for more information).

Then why would someone use the more complicated one? Maybe it's just their personal preferences or for the convenience that they may change the number of the dimensions later.

pjpj
  • 441
  • 1
  • 4
  • 20