Skip to content Skip to sidebar Skip to footer

Remove Non Repeating Characters From A List

I am trying to remove non repeating characters from a list in python. e.g list = [1,1,2,3,3,3,5,6] should return [1,1,3,3]. My initial attempt was: def tester(data): for x in d

Solution 1:

l=[1,1,2,3,3,3,5,6]

 [x for x in l if l.count(x) > 1][1, 1, 3, 3, 3]

Adds elements that appear at least twice in your list.

In your own code you need to change the line for x in data to for x in data[:]:

Using data[:] you are iterating over a copy of original list.

Solution 2:

There is a linear time solution for that:

def tester(data):
    cnt = {}
    for e indata:
        cnt[e] = cnt.get(e, 0) + 1return [x for x indataif cnt[x] > 1]

Solution 3:

This is occurring because you are removing from a list as you're iterating through it. Instead, consider appending to a new list.

You could also use collections.Counter, if you're using 2.7 or greater:

[a for a, b in collections.Counter(your_list).items() if b > 1]

Solution 4:

Another linear solution.

>>>data = [1, 1, 2, 3, 3, 3, 5, 6]>>>D = dict.fromkeys(data, 0)>>>for item in data:...    D[item] += 1...>>>[item for item in data if D[item] > 1]
[1, 1, 3, 3, 3]

Solution 5:

You shouldn't remove items from a mutable list while iterating over that same list. The interpreter doesn't have any way to keep track of where it is in the list while you're doing this.

See this question for another example of the same problem, with many suggested alternative approaches.

Post a Comment for "Remove Non Repeating Characters From A List"