-4

Let's say we have a list: x = [5, 5, 2, 5, 5, 3, 3, 4, 4]. How can I return the number which happens only once in this list, i.e. 2?

This question was asked while trying to solve the "Find the odd int" problem on Codewars. Initially I did not understand correctly the task, but could have solved it much easier, so read it carefully before solving :)

Finally following code was used to solve it (it's not entire solution, but the part of it, which is used after creating the dictionary out of the input):

return [int(k) for k,v in d.items() if v%2==1][0]

2 Answers2

3
>>> x = [5, 5, 2, 5, 5, 3, 3, 4, 4, 8]
>>> from collections import Counter
>>> c = Counter(x)
>>> [item[0] for item in c.items() if item[1]==1]
[2, 8]
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

You may use collections.Counter to achieve this. Below list comprehension will return list of all elements which occurred once in your list:

>>> from collections import Counter
>>> x = [5, 5, 2, 5, 5, 3, 3, 4, 4]

>>> [k for k, v in Counter(x).items() if v==1]
[2]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126