I am looking at this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440509

When I tried to do it, doesn't work. why?

>>> from sets import Set
>>> new_list = [2,34,5,5,6,6,7,2]
>>> print new_list
[2, 34, 5, 5, 6, 6, 7, 2]
>>> new_list = Set(new_list).elems
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'Set' object has no attribute 'elems'
>>>

set.Set has nothing named elems. Beyond that it is hard to say. Post a question to the author at ActiveState, or e-mail them directly if there is an address. Also, post some code with what it is you are trying to do so someone can come up with something that works.

What is the best way to eliminate duplicates in list using sets, if you can perserve the order, it will be good?

# set is builtin starting with Python24
 
new_list = [2,34,5,5,6,6,7,2]
print new_list  # [2, 34, 5, 5, 6, 6, 7, 2]
 
new_set = set(new_list)
print new_set  # set([2, 7, 34, 6, 5])

Shorter ...

# use set() to make a list unique, order is lost
mylist = [2, 34, 5, 5, 6, 6, 7, 2]
unique_list = list(set(mylist))
print unique_list  # [2, 7, 34, 6, 5]

... if you want to keep order ...

# to keep the order use a modified list comprehension
mylist = [2, 34, 5, 5, 6, 6, 7, 2]
ulist = []
[ulist.append(x) for x in mylist if x not in ulist]
print ulist  # [2, 34, 5, 6, 7]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.