Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 911
Abhay kumar Avatar asked Nov 08 '18 05:11

Abhay kumar


People also ask

How do I remove the first duplicate in a list Python?

If you just want to remove the first duplicate, you can create set, append elements to a new list if they are in the set while removing each element from the set as well. When an element is not seen, append the rest of the list.

How do you find no duplicates in Excel?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.


1 Answers

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))
like image 192
ShadowRanger Avatar answered Sep 28 '22 19:09

ShadowRanger