Lets say I have a list with integers.
lst = [1,2,3,3,2,1]
When I want to print ID's of all elements in the list i'm getting duplicated ID's. How can I prevent it?
Lets say I have a list with integers.
lst = [1,2,3,3,2,1]
When I want to print ID's of all elements in the list i'm getting duplicated ID's. How can I prevent it?
As sets preserve order in python 3.6+ you can do this:
for i in set(lst):
print(id(i))
Since sets cannot contain duplicate values
You can use this code if you care about the order in list, :(for more https://docs.python.org/3/library/collections.html#collections.OrderedDict)
from collections import OrderedDict
lst = [1,2,3,3,2,1]
for i in list(OrderedDict.fromkeys(lst)):
print(id(i))
If you don't care about the order, use this function:
l = [1,2,3,3,2,1]
def remove_duplicates(l):
return list(set(l))
for i in remove_duplicates(l) :
print(id(l))