# How to turn a Python array into Mathematica List?

I am running

a = RunProcess[\$SystemShell, "StandardOutput", "python2 fit.py"]


which returns

"[ 0.04044647 0.75243326 -0.42992283]\n[ 0.04163976 0.15076435 0.31245249]\n"

How to turn it into a Mathematica expression?

• I assume you are looking for something more sophisticated than ToExpression[StringReplace[..., {"[ " -> "{{", "]\n[ " -> "},{", "]" -> "}}", " " -> ","}]], right? – AccidentalFourierTransform May 11 '19 at 16:09
• Well, I thought there is something more direct, some FromPythonExpression or so. – corey979 May 11 '19 at 16:42
• There is an export type"Python expression" – user5601 May 11 '19 at 17:06

Python lists have to have commas in between the numbers. With that fixed, we can use ImportString on each line individually:

ImportString["[ 0.04044647, 0.75243326, -0.42992283]", "PythonExpression"]


{0.0404465, 0.752433, -0.429923}

• Hm, looks I need to figure out why python is giving me an array without commas :/ – corey979 May 11 '19 at 17:25
• @corey979 I would guess that you are using NumPy or something that uses NumPy under the hood, where the string representation of the array gives you space delimited arrays when printed. You could convert the NumPy array to a python list using tolist() and lists should be printed as comma delimited. For example, print(a.tolist()). – Tim Laska May 12 '19 at 0:15
• @TimLaska Indeed. Thanks! – corey979 May 12 '19 at 7:11

An inelegant but functional solution:

test = "[ 0.04044647 0.75243326 -0.42992283]\n[ 0.04163976 0.15076435 0.31245249]\n";

Select[ToExpression[StringSplit[test, {" ", "[", "]"}]], NumberQ]


{0.0404465, 0.752433, -0.429923, 0.0416398, 0.150764, 0.312452}

Or if the list should be divided by "\n" first:

ToExpression[StringSplit[StringSplit[test, "\n"], {" ", "[", "]"}]]


{{0.0404465, 0.752433, -0.429923}, {0.0416398, 0.150764, 0.312452}}