views:

92

answers:

5

I'm trying to remove duplicate items in a list through a dictionary:

def RemoveDuplicates(list):
    d = dict()

    for i in xrange(0, len(list)):
        dict[list[i]] = 1       <------- error here

    return d.keys()

But it is raising me the following error:

TypeError: 'type' object does not support item assignment

What is the problem?

+10  A: 

You should have written:

d[list[i]] = 1

But why not do this?

def RemoveDuplicates(l):
    return list(set(l))

Also, don't use built-in function names as variable names. It can lead to confusing bugs.

Mark Byers
+3  A: 

dict is the type, you mean d[list[i]] = 1.

Addition: This points out the actual error in your code. But the answers provided by others provide better way to achieve what you are aiming at.

Rasmus Kaj
+3  A: 
def remove_duplicates(myList):
    return list (set(myList))

From looking at your code it seems that you are not bothered about the ordering of elements and concerned only about the uniqueness. In such a case, a set() could be a better data structure.

The problem in your code is just to use a function argument name which is not the name of the built-in type list and later on the type dict in the expression dict[list[i]].

Shailesh Kumar
+3  A: 

In addition to what others have said, it is unpythonic to do this:

for i in xrange(0, len(lst)):
    do stuff with lst[i]

when you can do this instead:

for item in lst:
    do stuff with item
Dave Kirby
A: 

Note that using list(set(seq)) will likely change the ordering of the remaining items. If retaining their order is important, you need to make a copy of the list:

items = set()
copy = []
for item in seq:
    if not item in items:
        copy.add(item)
        items.append(item)
seq = copy
Robert Rossney