The Stack Overflow podcast is back! Listen to an interview with our new CEO.

6 of 10 deleted 1 character in body

# Union of two or more lists

I have a number of lists (only 3 shown here)



List1 = {{23, 24, 25, 26}, {23, 24, 25, 26, 27, 28}, {23, 24, 25, 26, 27, 28, 29}}
List2 = {{23, 24, 26, 30, 29}, {23, 24, 26, 29, 30, 31, 32}}
List3 = {{31, 33, 23}, {23, 31, 33, 35}, {23, 31, 33, 34, 35}, {23, 31, 33, 34, 35}}


I want to make a combine these lists in the following way: Union the last element of List1 with each element of List2, and add it to the end of List1, then Union the last element of List2 to all the elements of List3 and add them to the end of List1.

Producing

FinalList = {{23, 24, 25, 26}, {23, 24, 25, 26, 27, 28}, {23, 24, 25, 26, 27, 28,
29}, {23, 24, 25, 26, 27, 28, 29, 30}, {23, 24, 25, 26, 27, 28, 29,
30, 31, 32}, {23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}, {23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 35}, {23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35},{23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35}}


I should mention, the numbers are random, although here it appears as consecutive at some places.

EDIT: With @ciao's help, I have the solution

Union@FoldList[Union, Join[List1, List2, List3]]


However, it seems to drop repeated elements as it appears in List3.

 asked Jun 26 '15 at 22:40 HuShu 28411 silver badge1111 bronze badges