-1

This is a piece of homework for my programming course. We are asked to make a function that accepts a list of strings as a parameter, and then returns the same list of strings but without duplicates.
e.g:

>>> unique_list(['dog','cat','dog','fish'])
['dog','cat','fish']

Any information regarding the matter would be greatly appreciated.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
dehvud
  • 27
  • 5
  • Does the order in which you return the strings matter? – NPE Apr 09 '14 at 05:43
  • First time using this website, was not dissapointed, this is an excellent resource. Thank you to all who helped me in answering this question. – dehvud Apr 09 '14 at 23:09

2 Answers2

0

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'] 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Thank you, this is very useful information. I see I was missing the `append` option in my trials, now I can play around with it. Also, that `set` function looks incredibly useful aswell, will definently give that a go. – dehvud Apr 09 '14 at 23:05
  • Glad to be of help! :) – A.J. Uppal Apr 10 '14 at 00:00
0
def unique_list(subject):
    return list(set(subject))

This is what you can write in python 3.3

Shafiul
  • 2,832
  • 9
  • 37
  • 55