How can I most effectively check for unique items in a list?

let's say i have a list

li = [{'q':'apple','code':'2B'},
      {'q':'orange','code':'2A'},
      {'q':'plum','code':'2A'}]

What is the most efficient way to return the number of unique β€œcodes” in this list? In this case, the unique codes are 2, since only 2B and 2A are unique.

I could put everything on a list and compare, but is it really effective?

+5
source share
1 answer

Probably the most efficient simple way is to create a set of codes that will filter out uniques, and then get the number of elements in this set:

count = len(set(d["code"] for d in li))

, , , . , , , , .

+8

All Articles