-4

Suppose we have a list, where every item has its frequency: 1, 2, 3 , etc. Then, from this list, I would like to get another list where every item has a frequency 1.

For example, the original list is:

A = [1, 2, 3, 1, 2, 5, 6, 7, 8, 5]

The idea is to get another list such as:

B = [1, 2, 3, 5, 6, 7, 8]

How can I do it?

This is what I implemented in Python:

for i in range(10):
    k = i
    item1 = A[k]
    for j in range(k):
        l = j
        item2 = A[l]
        if (item1 != item2):
            B.append(item1)
            break

But I get:

B = [1, 2, 5]

Can someone please help me? Thanks in advance.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
rogwar
  • 143
  • 1
  • 1
  • 8

3 Answers3

0

I am not sure if there is a built-in function for this but I would rather do this:

def Remove(duplicate): 
    final_list = [] # make an empty list
    for num in duplicate: # iterate over the given list
        if num not in final_list: # if number is not in the list, push it to the list.
            final_list.append(num) 
    return final_list
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Taimoor Ali
  • 158
  • 1
  • 7
0

You can use unique_everseen in order to remove duplicates and preserve order:

from  more_itertools import unique_everseen

A = [1, 2, 3, 1, 2, 5, 6, 7, 8, 5]
B = list(unique_everseen(items))
print(B)
>>> [1, 2, 3, 5, 6, 7, 8]

If you don't have more_itertools installed on your machine, you can install it using PyPi:

pip install more-itertools
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
0

A good method for this is to use the 'set' data structure.

a = [1, 2, 3, 1, 2, 5, 6, 7, 8, 5]
a_prime=list(set(a))
print (a_prime)
Out:
[1, 2, 3, 5, 6, 7, 8]
Taimoor Ali
  • 158
  • 1
  • 7
bart cubrich
  • 1,184
  • 1
  • 14
  • 41