-1

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?

Example : enter image description here

roxz
  • 9
  • 1
  • 1
    It would be better to post your example code as a text inside `code`, not as a screenshot. – Kostas Mar 30 '21 at 16:38
  • I just wanted to show the output but thanks for the warning. I will be more careful next time. – roxz Mar 30 '21 at 16:42
  • Please add code and data as text ([using code formatting](//stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](//meta.stackoverflow.com/a/285557). Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data. – Machavity Mar 31 '21 at 17:26

3 Answers3

2

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

TruVortex_07
  • 280
  • 1
  • 3
  • 16
0
for i in range(len(lst)):
    if lst[i] not in lst[:i]:
        print(id(lst[i]))
Kostas
  • 99
  • 1
  • 2
  • 7
0

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)) 
Salio
  • 1,058
  • 10
  • 21