How can I combine
list1={{x1,y1},{x2,y2},{x3,y3}}
and
list2={{x4,y4},{x5,y5}}
to
list={{x1,y1},{x2,y2},{x3,y3},{x4,y4},{x5,y5}}
?
How can I combine
list1={{x1,y1},{x2,y2},{x3,y3}}
and
list2={{x4,y4},{x5,y5}}
to
list={{x1,y1},{x2,y2},{x3,y3},{x4,y4},{x5,y5}}
?
You need Join :
list = Join[list1, list2]
sometimes you would choose :
listU = Union[list1, list2]
The latter doesn't include duplicates, as the first approach could, if some of elements in list1 and list2 were common.
Edit
It should be emphasized that since for small lists different approaches (pointed out in the other answers) are elegant and quite satisfactory, however for big lists Join is much superior. We compare their efficiency in a few different cases :
lA1 = RandomReal[1, {500000, 2}];
lA2 = RandomReal[1, {500000, 2}];
Join[lA1, lA2]; // AbsoluteTiming // First
& @@@ {lA1, lA2}; // AbsoluteTiming // First
{lA1, lA2}~Flatten~1; // AbsoluteTiming // First
0.0210000 0.8090000 0.4620000
lB1 = RandomReal[1, {2500000, 2}];
lB2 = RandomReal[1, {1500000, 2}];
Join[lB1, lB2]; // AbsoluteTiming // First
& @@@ {lB1, lB2}; // AbsoluteTiming // First
{lB1, lB2}~Flatten~1; // AbsoluteTiming // First
0.0820000 3.1500000 1.9000000
lC1 = RandomReal[1, {300000, 2}];
lC2 = RandomReal[1, {900000, 2}];
Join[lC1, lC2]; // AbsoluteTiming // First
& @@@ {lC1, lC2}; // AbsoluteTiming // First
{lC1, lC2}~Flatten~1; // AbsoluteTiming // First
0.0220000 0.9320000 0.6640000
We can see that Join is roughly about 20-30 times faster than {list1, list2}~Flatten~1; and the latter is about 1.5-2 times faster than ## & @@@.
Union is that it sorts the list, and if you don't wish to do that, other ways must be found (see Mr.Wizard's answer, in particular).
– rcollyer
May 06 '12 at 14:36
And another:
## & @@@ {list1, list2}
Sequence that is then embedded in the outer list. +1
– rcollyer
May 06 '12 at 15:09
Sequence @@@ {list1, list2}.
– celtschk
May 06 '12 at 15:50
Apply on packed arrays, will unpack.
– Leonid Shifrin
May 06 '12 at 19:32
Since there's always more than one way to do things in Mathematica, here's another alternative:
{list1, list2} ~Flatten~ 1
The above uses infix notation, which might be a little hard to grok at first, but can make the code very readable for functions that take 2 arguments and have descriptive names.
For comparison, here is the same expression written in 3 other forms:
Flatten[{list1, list2}, 1] (* Matchfix *)
Flatten[#, 1] &@{list1, list2} (* Prefix *)
{list1, list2} // Flatten[#, 1] & (* Postfix *)
list1 ~List~ list2 ~Flatten~ 1
– celtschk
May 06 '12 at 15:42