How do I create a Python set with only one element?
set_display ::= "{" (expression_list | comprehension) "}"
Example:
>>> myString = 'foobar'>>> s = {myString}>>> sset(['foobar'])>>> s = {'spam'}>>> sset(['spam'])
Note that an empty {}
is not a set
, its a dict
.
Help on set
:
class set(object) | set() -> new empty set object | set(iterable) -> new set object
As you can see set()
expects an iterable and strings are iterable too, so it converts the string characters to a set.
Put the string in some iterable and pass it to set()
:
>>> set(('foo',)) #tupleset(['foo'])>>> set(['foo']) #listset(['foo'])