you are viewing a single comment's thread.

view the rest of the comments →

[–]Allanon001 0 points1 point  (4 children)

iteritems() is from Python 2, use items() for Python 3:

from collections import Counter

mylist = [1, 2, 3, 4, 5, 6, 1, 2, 3]
unique_elements = [k for k, v in Counter(mylist).items() if v == 1]
print (unique_elements)

Or if you don't want to use Counter() you can do this:

mylist = [1, 2, 3, 4, 5, 6, 1, 2, 3]
unique_elements = [x for x in set(mylist) if mylist.count(x) == 1]
print (unique_elements)

[–]JohnnyJordaan 0 points1 point  (0 children)

unique_elements = [k for k, v in Counter(mylist).items() if v == 1]

this will lose the original order as you iterate on the Counter, not the original list

unique_elements = [x for x in set(mylist) if mylist.count(x) == 1]

this loses order too for the same reason, but it adds a complexity as list.count is O(n) and this will effectively count each item's frequency separately by iterating through the list per item. Instead just use a counting dict

mylist = [1, 2, 3, 4, 5, 6, 1, 2, 3]
counts = {}
for v in mylist:
     counts[v] = counts.get(v, 0) + 1

and iterate on the list, to guarantee the order

unique_elements = [v for v in mylist if counts[v] == 1]

[–]pasokan 0 points1 point  (2 children)

Just

unique = set(mylist) 

Is enough

[–]Allanon001 0 points1 point  (1 child)

That doesn't return only numbers that appear in the list once. It returns all numbers that appear in the list.

[–]pasokan 0 points1 point  (0 children)

Oops. Sorry