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.
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.
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.
In 3.6 and higher, this is very easy. Now that dict
s 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With