glls
glls

Reputation: 2403

Removing repeated characters from a list in python

So, im trying to remove repeated characters from the following 2 lists I have, My code works for the Int's but not for my String's?!

Any tips? Code is as follows:

list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

list2 = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

for i in list:

    list.sort()
    compteur = 0

    while compteur < len(list):

        if i == list[compteur]:

            list.remove(list[compteur])
            compteur+=1
        elif i != list[compteur]:
            compteur+=1

Under for i in list: everything should be indented idk why i was not able to make it appear the correct way.

Upvotes: 0

Views: 7510

Answers (3)

Harwee
Harwee

Reputation: 1650

This is old question but I am leaving this answer here

from collections import Counter
def dup_remover(lst):
    return list(Counter(lst))

>>> dup_remover(list2)
['a', 'c', 'b', 'e', 'f', 'o', 'q', 'p', 'r', 't', 'v', 'x', 'z']

Upvotes: 0

Andr&#233; Teixeira
Andr&#233; Teixeira

Reputation: 2562

As you said that you are not allowed to make usage of sets, you can make it verifying each element and inserting it on a third unique elements list as:

int_list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

char_list = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

Example with int_list:

unique_list = []
for el in int_list:
    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

The result would be:

>>> print unique_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Upvotes: 3

Totem
Totem

Reputation: 7349

If you can't use sets, you could do this, it would work for both your lists.

int_list = [0,1,0,1,2,2,3,4,5,7,9,8,10,1,1,3,4,5,6,7,8,9,10]

ints = []
for i in int_list:
    if i not in ints:
        ints.append(i)
ints.sort()

>>> print ints
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And for your list of characters:

char_list = ['z','r','a','z','x','b','z','a','f','f','f','x','t','t','o','p','a','b','v','e','q','p','c','x']

chars = []
for i in char_list:
    if i not in chars:
        chars.append(i)
chars.sort()

>>> print chars
['a', 'c', 'b', 'e', 'f', 'o', 'q', 'p', 'r', 't', 'v', 'x', 'z']

Upvotes: 1

Related Questions