yoOwhatUP
yoOwhatUP

Reputation: 23

Removing duplicates using set

Basically, I want to do this with iteration from a lst in to a set and the printing it back to list. The problem I get is that I can't iterate through set.add(item). set.add() was perfectly fine when applying one value outside a loop but I can't get it to work inside a loop.

Using this function I am able to remove duplicates.

remove_duplicates(numbers):
    lst = []
    for i in numbers:
        if i not in lst:
            lst.append(i)
    return lst

However, I want to be able to do something like this.

Here is how far I was able to come.

lst = { }
lsto = [1, 1, 1, 2, 3, 4, 1, 2, 5, 7, 5]

for item in lsto:
    lst.add(item)

print(lst)

Thanks in advance!

Upvotes: 0

Views: 124

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

To match the first logic and keep order you can use an OrderedDict :

from collections import OrderedDict
lsto = [1, 1, 1, 2, 3, 4, 1, 2, 5, 7, 5]

print(OrderedDict().fromkeys(lsto).keys())
[1, 2, 3, 4, 5, 7]

The set by chance gives you the same order but sets are unordered collections so you cannot rely on getting any order.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

I think you mean this,

>>> lsto = [1, 1, 1, 2, 3, 4, 1, 2, 5, 7, 5]
>>> list(set(lsto))
[1, 2, 3, 4, 5, 7]

set(lsto) turns the iterable lsto into set which in-turn remove the duplicate elements. By again turning the set to list will give you a list at final.

Upvotes: 5

Related Questions