Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is set(None) invalid in python

Tags:

python

types

set

>>> set(None)
*** TypeError: 'NoneType' object is not iterable

is a problem but not this:

>>> a=set()
>>> a.add(None)

Why?

like image 968
Lelouch Lamperouge Avatar asked Oct 10 '11 22:10

Lelouch Lamperouge


2 Answers

As the error message tells you, set() expects an iterable.

set([None])

Note: the same is true for list, tuple, ...

like image 81
Karoly Horvath Avatar answered Sep 23 '22 04:09

Karoly Horvath


Because the set initializer takes an object that must be iterable, but add() will take any element as long as its hashable. Since NoneType is not iterable, it raises an exception.

class set([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

add(elem) Add element elem to the set.

iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.

In [18]: hash(None)
Out[18]: 39746304

In [19]: iter(None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/jon/<ipython console> in <module>()    
TypeError: 'NoneType' object is not iterable

In [21]: dir(None)
Out[21]: 
['__class__',  
 '__delattr__',  
 '__doc__', 
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__', 
 '__new__', 
 '__reduce__', 
 ...
 '__subclasshook__']

In [22]: dir([])
Out[22]:
[...  
 '__hash__',
 '__getitem__',
 ...  
 '__iter__',
like image 42
chown Avatar answered Sep 21 '22 04:09

chown