# [Numpy-discussion] Vector magnitude?

Zachary Pincus zpincus@stanford....
Wed Sep 5 13:49:45 CDT 2007

```Hello,

'len' is a (pretty basic) python builtin function for getting the
length of anything with a list-like interface. (Or more generally,
getting the size of anything that is sized, e.g. a set or dictionary.)

Numpy arrays offer a list-like interface allowing you to iterate
along their first dimension, etc. (*) Thus, len(numpy_array) is
equivalent to numpy_array.shape[0], which is the number of elements
along the first dimension of the array.

Zach

(*) For example, this is useful if you've got numerous data vectors
packed into an array along the first dimension, and want to iterate
across the different vectors.

a = numpy.ones((number_of_data_elements, size_of_data_element))
for element in a:
# element is a 1-D array with a length of 'size_of_data_element'

Note further that this works even if your data elements are multi-
dimensional; i.e. the above works the same if:
element_shape = (x,y,z)
a = numpy.ones((number_of_data_elements,)+element_shape)
for element in a:
# element is a 3-D array with a shape of (x,y,z)

On Sep 5, 2007, at 2:40 PM, Robert Dailey wrote:

>
> I was not able to find len() in the numpy documentation at the
> http://www.scipy.org/doc/numpy_api_docs/namespace_index.html
>
> Perhaps I'm looking in the wrong location?
>
> On 9/5/07, Matthieu Brucher <matthieu.brucher@gmail.com > wrote:
>
> 2007/9/5, Robert Dailey < rcdailey@gmail.com>: Hi,
>
> I have two questions:
>
> 1) Is there any way in numpy to represent vectors? Currently I'm
> using 'array' for vectors.
>
>
> A vector is an array with one dimension, it's OK. You could use a
> matrix of dimension 1xn or nx1 as well.
>
>
> 2) Is there a way to calculate the magnitude (length) of a vector
> in numpy?
>
> Yes, len(a)
>
> Matthieu
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion

```