Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently find the odds one out in a list?

Tags:

python

list

Say I have a list like

>>> l = [-10,-10,-10,-20,-10,-10]

Given you don't know it's -20, I want to find the position and the number of -20 in one line or maybe two. Any thoughts?

like image 602
tipsywacky Avatar asked Nov 17 '25 22:11

tipsywacky


2 Answers

This will find the least-common element:

>>> my_list = [-10,-10,-10,-20,-10,-10]
>>> from collections import Counter
>>> counter = Counter(my_list)
>>> min(counter, key=counter.get)
-20

To find the position, you could use my_list.index(min(counter, key=counter.get)).

Note this will not work for the odd-one-out in a list such as [1, 2, 9999, 3, 4], you might like to check out my answer here for a case such as that.

like image 149
wim Avatar answered Nov 20 '25 11:11

wim


Assuming that you want to find the items that appear only once:

>>> from collections import Counter
>>> l = [-10,-10,-10,-20,-10,-10]
>>> [i for i, n in Counter(l).iteritems() if n == 1]
[-20]
like image 26
devnull Avatar answered Nov 20 '25 12:11

devnull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!