How to find first value in a list having no duplicates?

  • A+
Category:Languages
l1 = ['A','B','C','D','A','B'] l2 = [] 

'C' is the first value in list l1, i want to create a function so that it returns C in l2.

 


In 3.6 and higher, this is very easy. Now that dicts preserve insertion order, collections.Counter can be used to efficiently count all elements in a single pass, then you can just scan the resulting Counter in order to find the first element with a count of 1:

from collections import Counter  l1 = ['A','B','C','D','A','B'] l2 = [next(k for k, v in Counter(l1).items() if v == 1)] 

Work is strictly O(n), with only one pass of the input required (plus a partial pass of the unique values in the Counter itself), and the code is incredibly simple. In modern Python, Counter even has a C accelerator for counting inputs that pushes all the Counter construction work to the C layer, making it impossible to beat. If you want to account for the possibility that no such element exists, just wrap the l2 initialization to make it:

try:     l2 = [next(k for k, v in Counter(l1).items() if v == 1)] except StopIteration:     l2 = []     # ... whatever else makes sense for your scenario ... 

or avoid exception handling with itertools.islice (so l2 is 0-1 items, and it still short-circuits once a hit is found):

from itertools import islice  l2 = list(islice((k for k, v in Counter(l1).items() if v == 1), 1)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: