Skip to content Skip to sidebar Skip to footer

Python Script To Remove Unique Elements From A List And Print The List With Repeated Elements In Proper Order

I have written a script to remove all unique elements from a list and print the list with only repeated elements: Below are some examples how the output list for an input list shou

Solution 1:

your script has a number of issues:

  • the classical if x in dict1.keys() => if x in dict1 to be sure to use the dictionary check instead of linear
  • no list comprehension: append in a loop, not as performant.
  • O(n^2) complexity because of the double loop

My approach:

You could count your elements using collections.Counter, then filter out a new list using a list comprehension using a filter on the number of ocurrences:

from collections import Counter

list1 = [1,2,1,1,3,5,3,4,3,1,6,7,8,5]

c = Counter(list1)
new_list1 = [k for k in list1 if c[k]>1]

print(new_list1)

result:

[1, 1, 1, 3, 5, 3, 3, 1, 5]

I may be wrong but, the complexity of this approach is (roughly) O(n*log(n)) (linear scan of the list plus the hashing of the keys in the dictionary and the lookup in the list comprehension). So, it's good performance-wise.

Post a Comment for "Python Script To Remove Unique Elements From A List And Print The List With Repeated Elements In Proper Order"