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

PythonPython 3.xSet

Python Problem Overview


If I have a string, and want to create a set that initially contains only that string, is there a more Pythonic approach than the following?

mySet = set()
mySet.add(myString)

The following gives me a set of the letters in myString:

mySet = set(myString)

Python Solutions


Solution 1 - Python

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

mySet = {'abc'}

Solution 2 - Python

For example, this easy way:

mySet = set([myString])

Solution 3 - Python

For Python2.7+:

set_display ::=  "{" (expression_list | comprehension) "}"

Example:

>>> myString = 'foobar'
>>> s = {myString}
>>> s
set(['foobar'])

>>> s = {'spam'}
>>> s
set(['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',))  #tuple
set(['foo'])
>>> set(['foo'])   #list
set(['foo'])

Solution 4 - Python

set(obj) is going to iterate trough obj and add all unique elements to the set. Since strings are also iterable, if you pass a string to set() then you get the unique letters in your set. You can put your obj to a list first:

set(["mystring"])

However that is not elegant IMO. You know, even for the creation of an empty dictionary we prefer {} over dict(). Same here. I wolud use the following syntax:

myset = {"mystring"}

Note that for tuples, you need a comma after it:

mytuple = ("mystring",)

Solution 5 - Python

If the set also isn't likely to change, consider using a frozenset:

mySet = frozenset([myString])

Solution 6 - Python

use mySet = {mystring}

 Python 3.6.9 (default, Sep 24 2019, 14:35:19)                                                                                             
 Type 'copyright', 'credits' or 'license' for more information                                                                             
 IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.                                                                       
                                                                                                                                           
 In [1]: def s(i):                                                                                                                         
     ...:     r = set()                                                                                                                     
     ...:     r.add(i)                                                                                                                      
     ...:     return r                                                                                                                      
     ...:                                                                                                                                   
                                                                                                                                           
 In [2]: %timeit s(1234)                                                                                                                   
  218 ns ± 5.99 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)                                                                
                                                                                                                                             
 In [3]: %timeit set([1234])                                                                                                               
  201 ns ± 3 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)                                                                  
                                                                                                                                             
 In [4]: %timeit {1234}                                                                                                                    
  51.7 ns ± 1.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThalecressView Question on Stackoverflow
Solution 1 - PythondstrombergView Answer on Stackoverflow
Solution 2 - PythonAnatoly ScherbakovView Answer on Stackoverflow
Solution 3 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 4 - PythonSzieberthAdamView Answer on Stackoverflow
Solution 5 - PythonSimeon VisserView Answer on Stackoverflow
Solution 6 - Pythonmatt2000View Answer on Stackoverflow