-1

My code can remove duplicate items but destroys the order of the list

ls = eval(input("Input a list:"))
lss = list(set(ls))
print(lss)

I searched and tried some codes but it isn't working for me.

krisssz
  • 65
  • 7
  • 2
    Don't use `eval(input(..))`. – Austin Apr 09 '20 at 11:26
  • What is this code you've found that hasn't worked? It would be a shame if we gave you that piece of code only to get a response from you that you've already tried it. – Hampus Larsson Apr 09 '20 at 11:28
  • If remove eval and input ['b','c','d','c','a','a'], the output becomes worst [',', 'd', '[', 'b', ']', 'a', "'", 'c'] – krisssz Apr 09 '20 at 11:30
  • Does this answer your question? [Get unique values from a list in python](https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python) – pavi2410 Apr 09 '20 at 11:31
  • https://stackoverflow.com/a/48028065/7595401 – pavi2410 Apr 09 '20 at 11:31
  • @ven, `eval` is dangerous. It should not be used with user inputs. Unknown users can input and harm your system. Your best bet is to form list in your code itself. Also, set is unordered. – Austin Apr 09 '20 at 11:40
  • @Austin I'll keep in mind, thanks – krisssz Apr 09 '20 at 11:53

2 Answers2

0

The order is not preserved because you convert your list to set, which is unordered, unique collection.

Try this one:

from collections import OrderedDict
items = eval(input("Input a list:"))
print(list(OrderedDict.fromkeys(items)))

# for example:
items = [1, 2, 0, 1, 3, 2]
print(list(OrderedDict.fromkeys(items)))
# output: [1, 2, 0, 3]

Gabio
  • 9,126
  • 3
  • 12
  • 32
0
lst = input("Input List: ")
lst2 = []
for i in lst:
    if i not in lst2:
        lst2.append(i)

print(lst2)

Apologies for my previous failed attempt. Hopefully this one works

Benjamin Luo
  • 131
  • 8