Search code examples
pythoncode-duplicationitems

Avoid duplicate items Python


I am having an issue with duplicate items in a list in python.

For example I have this list

i = ['hello', 'hi', 'bye', 'welcome', 'hi', 'bye'] 

I want to print every item once, even if it's duplicated print it once.

Is there any way to do it in python?


Solution

  • If the order doesn't matters, then you can use a set:

    print(set(i))
    

    Otherwise you can do something like this:

    seen = set()
    for e in i:
        if e not in seen:
            print(e)
            seen.add(e)