I have a large nested list of rules, wherein elements which have repeated entries on the LHS of the rules should be deleted. For instance

lis:={{a1 -> x1, a2 -> x2, a3 -> x3}, {b1 -> y1, b1 -> y2}}


GatherBy[#, #[[1]] &][[All, 1]] & /@ lis

gives the desired output

{{a1 -> x1, a2 -> x2, a3 -> x3}, {b1 -> y1}}

However, this obviously takes a while to perform if the list is large, since I am iterating through the list. I tried a few things using Sow and Reap without much success.

  • 2
    $\begingroup$ Is there a reason you are not using DeleteDuplicates for this? $\endgroup$ Jul 11, 2023 at 10:13

2 Answers 2


If you want rules without duplicate keys, you really should be using Associations instead of lists of rules. They're much faster and automatically handle key duplicates. In this case, you could do:

Map[Normal @ Reverse @ Association[Reverse[#]]&, lis]

Remove the Normal if you want to stick with Associations (which I recommend). Note also that this is generally faster than DeleteDuplicatesBy[First].

  • $\begingroup$ (+1) Nice, Sjoerd! :-) $\endgroup$ Jul 11, 2023 at 11:21
  • $\begingroup$ Great thanks! I didn't know that about Associations. This seems to be the fastest solution. $\endgroup$ Jul 11, 2023 at 12:46
Map[DeleteDuplicatesBy[First]] @ lis
{{a1 -> x1, a2 -> x2, a3 -> x3}, {b1 -> y1}}

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.