Pham Hung
Pham Hung

Reputation: 83

Remove all same characters in list

I want to know how to remove all repeated characters in this list below (not use set()). I tried to use remove() in list but it just can remove first occurence of value.

Ex: input = [23,42,65,73,5,2,73,51] output = [23,42,65,5,2,51]

def number_repeated(lst):
    index = int(input('Remove index : '))
    a = 0
    for num in lst:
        if num == index:
            a += 1
    print('The number of digits are repeated: {}'.format(a))
    list(set(lst)).remove(index)
    return lst

print(number_repeated([23, 42, 65, 73, 5, 2, 73, 51]))

Output:

[65, 2, 5, 42, 51, 23]

Also, why in this code above when I use set() is the output not sorted?

Upvotes: 1

Views: 148

Answers (2)

Hirusha Fernando
Hirusha Fernando

Reputation: 1305

Try this

def myFunc(lst):    
    list2 = []

    for x in lst:
        if not x in list2:
            list2.append(x)

    list2 = sorted(list2)
    return list2

print(myFunc([23,42,65,73,5,2,73,51]))

Output:

[2, 5, 23, 42, 51, 65, 73]

Upvotes: 1

Harshana
Harshana

Reputation: 5496

You can use collections.Counter() to remove all the duplicates:

Example:

from collections import Counter

originalList = [23,42,65,73,5,2,73,51]

filteredList = [k for k, v in Counter(originalList).items() if v == 1]

print(filteredList)

Upvotes: 2

Related Questions