0

I have a list (ex: [1, 2, 2, 3, 4, 3]) and I need to only keep the first occurrence of any of the elements in the list (ex: the list should become [1, 2 ,3, 4]). I know that I could do something like this:

badList = [1, 2, 2, 3, 4, 3]
goodList = []
for element in badList:
    if element in goodList:
        continue
    goodList.append(element)
print (goodList)

However, this is a very messy solution, and I am hoping there is a more elegant way.

Mr. Hax
  • 195
  • 1
  • 1
  • 10

2 Answers2

2
from collections import OrderedDict
list(OrderedDict.fromkeys(badList))
[1, 2, 3, 4]

credit to @poke

Peter Dolan
  • 1,393
  • 1
  • 12
  • 26
0

Just convert to a set then back to a list:

goodList = list(set(badList))
Adriano Martins
  • 1,788
  • 1
  • 19
  • 23