Sets Module Bug?

C

Chris S.

from sets import *
>>> Set((1,2,3)) Set([1, 2, 3])
>>> Set([1,2,3]) Set([1, 2, 3])
>>> Set(([1,2,3],[4,5,6]))
Traceback (most recent call last):
File "<input>", line 1, in ?
File "sets.py", line 399, in __init__
self._update(iterable)
File "sets.py", line 344, in _update
data[element] = value
TypeError: list objects are unhashable

How can a Set using a tuple or list be ok, but not a tuple of lists?
 
I

Irmen de Jong

Chris said:
from sets import *
Set((1,2,3)) Set([1, 2, 3])
Set([1,2,3]) Set([1, 2, 3])
Set(([1,2,3],[4,5,6]))
Traceback (most recent call last):
File "<input>", line 1, in ?
File "sets.py", line 399, in __init__
self._update(iterable)
File "sets.py", line 344, in _update
data[element] = value
TypeError: list objects are unhashable

How can a Set using a tuple or list be ok, but not a tuple of lists?

Because "list objects are unhashable", as Python told you :)
AFAIK the sets module is built upon the dict type, it uses (requires)
the elements of the set to be hashable for efficient containment tests.
The library reference of the sets module also says:
"All of the elements in iterable should be immutable or be transformable to an immutable
using the protocol described in section 5.13.3. "

--Irmen
 
M

Marek =?iso-8859-2?Q?Baczy=F1ski?=

Dnia Mon, 02 Aug 2004 05:25:50 -0400, Chris S. napisa³(a):
How can a Set using a tuple or list be ok, but not a tuple of lists?

Because tuples can't be changed once they're constructed (= immutable.)
You'd get the same error if you tried to do

Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
d = {[1,2]: 'foo'}
TypeError: list objects are unhashable
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

Set((1,2,3))
[...]
How can a Set using a tuple or list be ok, but not a tuple of lists?

I think you are confused by the syntax above. This expression constructs
a Set object, and fills it with the members of the tuple. In no way does
the Set "use" the tuple - once the Set is created, the tuple goes away.

So you should have asked "How can a Set containing numbers be ok, but
not a Set containing lists?", to which the other two posters gave the
right answer.

Regards,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top