Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have a function which can accept either a list or a numpy array.

In either case, the list/array has a single element (always). I just need to return a float.

So, e.g., I could receive:

list_ = [4]

or the numpy array:

array_ = array([4])

And I should return

 4.0

So, naturally (I would say), I employ float(...) on list_ and get:

TypeError: float() argument must be a string or a number

I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.

Based on the success with the numpy array conversion to float this lead me to the approach:

float(np.asarray(list_))

And this works when list_ is both a Python list and when it is a numpy array.

Question

But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?

share|improve this question
    
Can't you use slicing: float(list_[0]) = 4.0 – Kyrubas May 18 '15 at 19:17
    
either float(list_[0]) or float(''.join(list_)) – farhawa May 18 '15 at 19:21
up vote 2 down vote accepted

Just access the first item of the list/array, using the index access and the index 0:

>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4

This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

>>> float(list_[0])
4.0
share|improve this answer

I would simply use,

np.asarray(input, dtype=np.float)[0]
  • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.
  • if input is a list, np.asarray makes sure the output is of the right type.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.