2

What is going on here? How can I check that a has length?

>>> import numpy as np
>>> a = np.array(3)
>>> hasattr(a , '__len__')
True
>>> len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: len() of unsized object

Here, python considers a to not have length:

>>>a.shape
()

I am using python 2.7.3 and numpy 1.8.0.

Thanks.

1
  • Yair, both the title and this 2nd revision of your question deleted part of your question, so the answer appears unconnected to the question. Can you please fix it? It's very confusing. Commented Aug 25, 2018 at 2:29

1 Answer 1

1

Hm, maybe I am missing something here, but why don't you check for types?

import numpy as np

def make_ary(item):
    if not isinstance(item, list):
        ary = np.array([item])
    else:
        ary = np.array(item)
        ary = ary.ravel()
    return ary

And then:

a = [1,2,3]
b = 3
c = [ [1] , [2] ,[3] ]


>> make_ary(a)
array([1, 2, 3])

>> make_ary(b)
array([3])

>> make_ary(c)
array([1, 2, 3])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer but that was solved by a mysterious stranger that erased their comment. I'll just use np.ravel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.