3
$\begingroup$

Let's say I have 4 lists:

list1 = {a,b,c,d};
list2 = {e,f,g,h};
list3 = {i,j,k,l};
list4 = {m,n,o,p};

I can combine them using Join

Join[list1, list2, list3, list4]

My question is if there's another way to do this in such a way that I could reuse the code for 8 or 10 (or even 100) lists without having to type out each name (list1, list2. etc) separately? Thanks.

$\endgroup$
  • 6
    $\begingroup$ Join @@ Table[ToExpression["list" <> ToString@i], {i, 1, 4}] $\endgroup$ – jiaoeyushushu Sep 19 '17 at 2:24
  • $\begingroup$ Thank you. That works. $\endgroup$ – John Muse Sep 19 '17 at 19:39
3
$\begingroup$

Using indexed objects:

list[1] = {a, b, c, d};
list[2] = {e, f, g, h};
list[3] = {i, j, k, l};
list[4] = {m, n, o, p};

Array[list, 4, 1, Join]
{a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p}

Joining lists in a different order:

list /@ {2, 1, 4, 3} // Catenate
{e, f, g, h, a, b, c, d, m, n, o, p, i, j, k, l}

For versions 10 and later using Associations can have advantages.

Clear[list]

list = <||>;
list[1] = {a, b, c, d};
list[2] = {e, f, g, h};
list[3] = {i, j, k, l};
list[4] = {m, n, o, p};

Catenate[list]
{a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p}

Related examples:

$\endgroup$
2
$\begingroup$

Ultimately, the answer by @Mr.Wizard is the way to create and manipulate many lists. But, that doesn't answer OP's question if one can't create the lists oneself and need to deal with lists already created with complicated names.

Using Names gives a list of the names of symbols that match the string or pattern,

Names["list*"]
(* {"list1", "list2", "list3", "list4"} *)

Therefore adding ToExpression and Catenate

Catenate[ToExpression /@ Names["list*"]]

(* {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p} *)

So, this answer your question, but ultimately the advisable implementation is the one by @Mr.Wizard.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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