Home > Net >  How can I make my list return each element only once in a list?
How can I make my list return each element only once in a list?

Time:11-10

So I wrote this code to return back every string in the given lst: list once. Here is my code

def make_unique(lst: list[str]):
    s = []
    for x in lst:
        if lst.count(x) == 1:
           s.append(x)
        else:
           return(x)
    return s

When I put in the input:

print(make_unique(lst=['row','mun','row']))

The output returns

row

but I want my output to return

['row','mun']

which is basically all the strings in the list printed once. How can I do this??

CodePudding user response:

Why not you try this one line short code to remove duplicates from your list and make it unique

def make_unique(lst):
    return list(dict.fromkeys(lst))

print(make_unique(['row','mun','row'])) #['row','mun']

CodePudding user response:

Easy way to do this is turn the list into a set. A set only shows each item once and thats what you want.

lst=['row','mun','row']
setLst = set(lst)
for elem in setLst:
    print(elem)

CodePudding user response:

You can use set.

lst=['row','mun','row']
print(set(lst))
  • Related