Removing duplicate elements in a list with python

3

I have to do a function and I am not able to develop logic. It is as follows:

  

Write the remove_repetitions function that receives a list of integers as a parameter, checks to see if such a list has repeated elements, and removes them. The function should return a list corresponding to the first list, without repeated elements. The returned list must be sorted.

Tip: You can use lista.sort() or sorted(lista) .

    
asked by anonymous 24.03.2017 / 21:48

2 answers

6

A pythonic function to solve this problem would be:

def remove_repetidos(lista):
    l = []
    for i in lista:
        if i not in l:
            l.append(i)
    l.sort()
    return l

lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]

lista = remove_repetidos(lista)
print (lista)

Output:

>>>[1, 2, 3, 4, 6, 7, 8, 9, 10]

It's quite easy to see how the function works, so I'll omit more explanations.

    
24.03.2017 / 23:11
2

The list must be sorted, but in the same order as the original, or can you sort later?

I say this because set() is used just for this and is quite efficient even. In general you should avoid reprogramming what is already in the default library.

>>> lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]
>>> sorted(set(lista))
[1, 2, 3, 4, 6, 7, 8, 9, 10]

If you need to keep the same order as the original list see this answer: link

Or create a OrderedSet that would be the equivalent of a collections.OrderedDict only for lists. It works well too.

    
05.08.2017 / 21:05