vishrut pundir
vishrut pundir

Reputation: 1

Using numpy.ndarray.ndim(arr) directly get the number of dimensions

Can i directly use the command numpy.ndarray.ndim(arr) to get the no. of dimensions for an array ?? without importing numpy. Is it possible ??

Upvotes: 0

Views: 133

Answers (3)

hpaulj
hpaulj

Reputation: 231335

In [954]: import array                                                                                 
In [955]: a = array.array('i')                                                                         
In [956]: a.fromlist([1,2,3])                                                                          
In [957]: a                                                                                            
Out[957]: array('i', [1, 2, 3])
In [958]: len(a)                                                                                       
Out[958]: 3

Like a list, a has a len. It does not have a ndim:

In [959]: a.ndim                                                                                       
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-959-2cb81154a11f> in <module>
----> 1 a.ndim

AttributeError: 'array.array' object has no attribute 'ndim'

ndim is a property of a numpy.ndarray. It's not relevant to list or to array. If given one of thosr, np.ndim first converts it np.asarray(a):

In [960]: np.ndim(a)                                                                                   
Out[960]: 1                            # always 1
In [961]: np.ndim([1,2,3])                                                                             
Out[961]: 1

While lists can be nested, array.array has to contain a predefined element type, as documented. It does not have a general object type, so will always be 1 dimensional.

Upvotes: 0

Aly Hosny
Aly Hosny

Reputation: 827

no, but you can use the array attribute arr.ndim to get it. ndarray.ndim

Upvotes: 1

Błotosmętek
Błotosmętek

Reputation: 12927

No, without importing a module you can't use anything defined in that module.

Upvotes: 0

Related Questions