QBoard » Advanced Visualizations » Viz - Python » 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?

  • 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??

     
      November 10, 2021 1:03 PM IST
    0
  • 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)
      November 27, 2021 10:34 AM IST
    0
  • 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']
      November 17, 2021 12:57 PM IST
    0