0

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'
>>>
3
Contributors
3
Replies
11
Views
9 Years
Discussion Span
Last Post by vegaseat
0

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.

0

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

0
# 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]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.