Is it faster to union sets or check the whole list for a duplicate?

前端 未结 4 1548
攒了一身酷
攒了一身酷 2021-02-06 01:18

Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union.

4条回答
  •  梦谈多话
    2021-02-06 01:41

    The fastest thing you can do is build two sets from the lists and take the union of them. Both set construction from list and set union are implemented in the runtime, in very optimized C, so it is very fast.

    In code, if the lists are l1 and l2, you can do

    unique_elems = set(l1) | set(l2)
    

    EDIT: as @kriss notes, extending l1 with l2 is faster. This code however doesn't change l1, and works also if l1 and l2 are generic iterables.

提交回复
热议问题