# How do I export/import lists with their assigned names?

I want to write lists of expressions into an output file with names assigned to each list. Later I want to import them in a new notebook for further use.

Example.

list1={{a^2,b^2},{a+b,a^3},{a-b,b^3}};
list2={{c^2,d^2},{c+d,c^3},{d-c,d^3}};


I want to export them to a single file.

Open["out.dat"]
Export["out.dat",{list1,list2},"Text"]
Close["out.dat"]


which results:

cat out.dat
{{a^2, b^2}, {a + b, a^3}, {a - b, b^3}}
{{c^2, d^2}, {c + d, c^3}, {-c + d, d^3}}


Now to import them in a new notebook:

input=Import["out.dat","Text"];
list1=input[[1]];
list2=input[[2]];


Rather a convenient approach would be to save the (preferably customized) names of the lists as well. The option I found is using Save :

Save["out1.dat",{list1,list2}];


which results in

**cat out1.dat**
list1 = {{a^2, b^2}, {a + b, a^3}, {a - b, b^3}}
list2 = {{c^2, d^2}, {c + d, c^3}, {-c + d, d^3}}


This is precisely what I wanted. However, there is one exception. Assume that the original names of the lists are not as simple as list1,list2 but something like

 list["MyList"<>"1"]={{a^2,b^2},{a+b,a^3},{a-b,b^3}};
list["MyList"<>"2"]={{c^2,d^2},{c+d,c^3},{d-c,d^3}};


Here Save does not work as before as it needs only symbols and strings. This is where I need some help:

How do I save these types of names in a file with the Lists assigned to it?

In this case, the expected output would be

 cat out.dat
list["MyList1"]={{a^2,b^2},{a+b,a^3},{a-b,b^3}};
list["MyList2"]={{c^2,d^2},{c+d,c^3},{d-c,d^3}};


Is there any way to achieve this?

EDIT: I realized that Save can be used in this case as well.

Save["out.dat",list]


will give the output as

 list["MyList1"]={{a^2,b^2},{a+b,a^3},{a-b,b^3}}
list["MyList2"]={{c^2,d^2},{c+d,c^3},{d-c,d^3}}


However, in this case, it writes ALL occurrences of list[_ _ _]. This is therefore not as flexible as one wants it to be.

• Well, I just realized that Save can also handle this. Apparently Save["out.dat",list] will save the functions with the names although without the last ";" But its fine I think. In any case I would appreciate if any alternative approach is out there. Oct 2, 2023 at 11:42

As pointed Save["out.dat",list] could be a suboptimal solution. However, this has drawbacks in that it does not provide flexibility and tries to write every function in the output file.

A better approach would be to use Export along the following line:

 Export["out.dat",
{"list[\"MyList"<>"1\"] = ", list["MyList"<>"1"], ";",
"list[\"MyList"<>"2\"] = ", list["MyList"<>"2"], ";"}, "List"];


The result is very close to the expected output (except the line breaks):

cat out.dat

list["MyList1"] =
{{a^2, b^2}, {a + b, a^3}, {a - b, b^3}}
;
list["MyList2"] =
{{c^2, d^2}, {c + d, c^3}, {-c + d, d^3}}
;