Use the following code:
>>> def unique_list(mylist):
... copy = []
... for k in mylist:
... if k not in copy:
... copy.append(k)
... return copy
...
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 3, 2]
>>> unique_list(['dog','cat','dog','fish'])
['dog', 'cat', 'fish']
The for
loop loops over every item in mylist
. If the item is already in copy
, it does nothing. Otherwise, it adds the item to copy. At the end, we return the 'unduplicatified' version of mylist
, stored in copy
.
Or a one-liner would be:
>>> def unique_list(mylist):
... return list(set(mylist))
...
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 2, 3]
>>> unique_list(['dog','cat','dog','fish'])
['fish', 'dog', 'cat']