0
How do I remove duplicates from a list but keep the order?
I know sets remove duplicates, but they also change the order. If I have: nums = [1, 2, 2, 3, 1, 4] I want the output to be: [1, 2, 3, 4] but in the same order they appeared. How do I do that?
3 Answers
+ 4
SAIFULLAHI KHAMISU a Python dictionary behaves like an ordered set. Add your list to the keys of a dict(). The dict will remove duplicates as they are added and keep the original order. Then you may extract the dictionary keys into a list.
+ 3
SAIFULLAHI KHAMISU use set to remove duplicates and an array to preserve order.
https://sololearn.com/compiler-playground/cvyZlUxf79vN/?ref=app
+ 2
you can always do it manually, just iterate through the list and pick out unique elements into a new list. To make sure they are unique, you can just check if the element is already in the new list. That would take n^2 time complexity though (due to the double looop), so if that's something u care about, you can improve it by using a hashmap instead of a list to store found elements (dictionary in python).