Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to convert a numpy array to list.

input is :

s = [ 6.72599983 -7.15100002  4.68499994]

i want output as :

s = [6.72599983, -7.15100002, 4.68499994]

how I will do this in python?

share|improve this question

closed as unclear what you're asking by Bakuriu, aIKid, Slater Tyranus, user2357112, Benjamin Bannier Jan 8 '14 at 7:47

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

    
Doesn't look too hard ... have you made any attempts? –  mgilson Jan 8 '14 at 7:22
    
yes it has type <type 'numpy.ndarray'> –  sam Jan 8 '14 at 7:23
    
possible duplicate of Converting string that looks like a list into a real list - python –  alvas Jan 8 '14 at 7:24
1  
Then you don't have a string, you have a numpy array -- to get a list, simply use list(s). But if you thought you had a string, maybe you don't need to convert it... arrays are pretty good too :) –  mgilson Jan 8 '14 at 7:24
3  
@sam You should write the question properly. If s is numpy.ndarray why the hell do you write that it is a string and make up the code in the question to make sure to hide this? -1 -- learn to at least search the documentation before asking a question. –  Bakuriu Jan 8 '14 at 7:29

3 Answers 3

up vote 1 down vote accepted

If you have a numpy.ndarray, then try this:

>>> import numpy
>>> lst = [6.72599983, -7.15100002, 4.68499994]
>>> numpy.asarray(lst)
array([ 6.72599983, -7.15100002,  4.68499994])
>>> list(numpy.asarray(lst))
[6.7259998300000001, -7.1510000199999997, 4.68499994]

If you have wrongly casted the numpy.array into a string, then you need to use that cleaning trick with ast to get it into a list.

>>> import ast, numpy
>>> s = str(numpy.asarray(lst))
>>> s
'[ 6.72599983 -7.15100002  4.68499994]'
>>> list(ast.literal_eval(",".join(s.split()).replace("[,", "[")))
[6.72599983, -7.15100002, 4.68499994]
share|improve this answer
8  
It's missing the commas. ast won't help –  mgilson Jan 8 '14 at 7:23
    
@mgilson, edited, i was typing too slowly. –  alvas Jan 8 '14 at 7:39

Your question still is quite unclear.

If s is really of type 'numpy.ndarray' and not a string (as the older version of your question suggested), then just do

s = list(s)

and s will become a list.

share|improve this answer

s.split() should work.

You can find solution here: Python - convert string to list

share|improve this answer

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