Skip to content Skip to sidebar Skip to footer

How To Get Non-repeated Elements In A List

I want non repeating elements in a list. Here it is. A=[1, 2, 3, 2, 5, 1] Required Output: [3,5] set() gives [1, 2, 3, 5] Please let me know to achieve this task.

Solution 1:

You can use the count() method from the list object to get a count equal to 1:

>>>A=[1, 2, 3, 2, 5, 1]>>>unique=[i for i in A if A.count(i)==1]>>>unique
[3, 5]

Alternatively the Counter() class from the collections module can be used:

A = [1, 2, 3, 2, 5, 1]

c = Counter(A)

print [key for key, count in c.iteritems() if count==1]

Solution 2:

Use Counter and defaultdict from collections:

from collections import defaultdict
from collections import Counter

A = [1 ,2 ,3 ,2 ,5, 1]
# create a mapping from each item to it's count
counter = Counter(A)

# now reverse the mapping by using a defaultdict for convenience
countmap = defaultdict(list)

for k, v in counter.iteritems():
    countmap[v].append(k)

# take all values that occurred onceprint countmap[1] # [3, 5]

If you're interested in what the mappings are you can print them:

The counter:

Counter({1:2,2:2,3:1,5:1})

The countmap:

defaultdict(<type'list'>, {1: [3, 5], 2: [1, 2]})

To manually create the counter you can use this function:

defmake_counter(lst):
    counter = dict()
    for item in lst:
        if item in counter:
            counter[item] += 1else:
            counter[item] = 1return counter

make_counter(A)

Output:

{1:2, 2:2, 3:1, 5:1}

Solution 3:

#!/usr/bin/python3from collections import Counter
from functools import reduce


# Initialize Variable
A = [1, 2, 3, 2, 5, 1]

# iterating style
result1 = [key for key, count inCounter(A).items() if count == 1]

# functional style
result2 = reduce(
    lambda acc, pair: acc + [pair[0] if pair[1] == 1else acc,
    Counter(A).items(), [])

Solution 4:

Plain vanilla python, no imports needed:

Use a set to collect all elements you find, remove them and move to other set if you find them again - this is faster by a marging then using count(..) as Tanveer proposes.

A = [1, 2, 3, 2, 5, 1]
found = set()
found_again = set()

for a in A:
    if a in found_again:
        continueif a in found:
        found.remove(a)
        found_again.add(a)
    else:
        found.add(a)

print(list(found))

Output:

[3,5]

Post a Comment for "How To Get Non-repeated Elements In A List"