Search code examples
pythonsetiterable

Why does building a set fail when using set(int)?


I can do

>>> s = {1}
>>> type(s)
<class 'set'>

but

>>> s = set(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

What is the difference?


Solution

  • The difference is that the set() constructor takes an iterable. A single number is not an iterable.

    s = set((1,))