# Join nested lists if first element is within another list

I have a list like:

list1={{1, 16}, {1, 14}, {1, 3}, {1, 18}, {1, 2}, {1, 17}, {2, 17}, {2, 18}, {3, 14},{4,10}}


I would like to see if the first element of one nested list is an element of the first nested list and if so, append the second element of this list to the first list. Such that:

list2={{1, 16, 14, 3, 18, 2, 17}, {2, 17,...}, {3, 14,...},...}


My aim is to form a nested list of the chains of connected data. Any help at all would me much appreciated.

• Shouldn't it be list2={{1, 16, 14, 3, 18, 2, 17, 2, 17,...}, {3, 14,...},...} because 2 was already part of the first list at that point?  Commented Dec 8, 2017 at 15:42
• Does GroupBy[list1, First -> Last] work for you? Commented Dec 8, 2017 at 15:51

KeyValueMap[## & @@@ {##} &] @ GroupBy[First -> Last] @ list1


{{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}}

• Another (longer, but possibly more readable for people who don't like too many #s and @s) way using GroupBy is MapIndexed[Insert[#1, First@#2, 1] &, List @@ GroupBy[list1, First -> Last]]. Commented Dec 9, 2017 at 12:41

This would work:

DeleteDuplicates@Flatten@# &/@ GatherBy[list1, First]

(* {{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}} *)

• You can use this without pure function DeleteDuplicates /@ Flatten /@ GatherBy[list1, First] Commented Dec 8, 2017 at 16:27
• You can also Join instead of Flattening: DeleteDuplicates /@ Join @@@ GatherBy[list1, First]. Commented Dec 9, 2017 at 12:34
Rule @@@ list1 // Merge[#, Map@Sequence] & // KeyValueMap[List, #] & //
Map[FlattenAt[#, -1] &]


{{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}}

• Or shorter: KeyValueMap[Flatten@*List]@Merge[# &]@MapApply[Rule]@list1`
– eldo
Commented Sep 8, 2023 at 10:41