1

I need the element that appears only occur once. (python)

For example the result for

mylist = ['a', 'a', 'a', 'a', 'b', 'c']

would be

2
A. Wilson
  • 43
  • 4

4 Answers4

7

You can use collections.Counter to count the number of occurrences of each distinct item, and retain only those with a count of 1 with a generator expression:

from collections import Counter
sum(1 for c in Counter(mylist).values() if c == 1)

This returns: 2

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

This situation looks like a pure Set structure. If I were you I would turn the array to set and check the size of it.

You can check examples how to do it here

Mickey Hovel
  • 982
  • 1
  • 15
  • 31
  • That would output 3 for `['a', 'a', 'a', 'a', 'b', 'c']`. OP wants to count the number of elements which only occur once, so `b` and `c`. – glhr Apr 18 '19 at 17:56
0

You basically want to iterate through the list and check to see how many times each element occurs in the list. If it occurs more than once, you don't want it but if it occurs only once, you increase your counter by 1.

count = 0

for letter in mylist:
  if mylist.count(letter) == 1:
    count += 1

print (count)
Darren Yong
  • 54
  • 1
  • 5
  • 1
    You're going to count 'a' four times but it's going to work. I prefer the Counter approach, though. – Eric Darchis Apr 18 '19 at 18:02
  • @EricDarchis How do you think the counter does it? If we're talking complexity-wise I think they're the same. If we're talking simplicity and readibility, I prefer this one. It's just simple. – Adham Zahran Apr 18 '19 at 18:04
  • Please explain your answer. Do not give code-only answers. – StefanG Apr 18 '19 at 18:05
  • 1
    @AdamZahran no, this is quadratic time, whereas a `Counter` based approach is linear time – juanpa.arrivillaga Apr 18 '19 at 18:09
  • 1
    The Counter is a special dictionary. So you browse the array only once and increment the counters in the dict as you go. As @juanpa.arrivillaga states, you're browsing the array len(mylist)*len(mylist) times instead of len(mylist)+len(unique items). The drawback of the counter is that it uses more memory. But if that's of any matter, the n² complexity is going to be much worse anyway. – Eric Darchis Apr 18 '19 at 18:15
-1

This should work for you:

len(set(mylist))

It does require your values to be hashable.

brunns
  • 2,689
  • 1
  • 13
  • 24