4
$\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$
2
  • 6
    $\begingroup$ Join @@ Table[ToExpression["list" <> ToString@i], {i, 1, 4}] $\endgroup$ Commented Sep 19, 2017 at 2:24
  • $\begingroup$ Thank you. That works. $\endgroup$
    – John Muse
    Commented Sep 19, 2017 at 19:39

2 Answers 2

5
$\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$
3
$\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 and acknowledge you have read our privacy policy.

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