How do I create a Python set with only one element? How do I create a Python set with only one element? python-3.x python-3.x

How do I create a Python set with only one element?


In 2.7 as well as 3.x, you can use:

mySet = {'abc'}


For example, this easy way:

mySet = set([myString])


For Python2.7+:

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'])