Episode #125 of the Stack Overflow podcast is here. We talk Tilde Club and mechanical keyboards. Listen now

9 of 10 deleted 11 characters 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 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.

Edit 2

Fidgeting around for a bit, I realized on dropping the outer Union, the problem is solved.

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