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)
In 2.7 as well as 3.x, you can use:
For example, this easy way:
set(obj)
is going to iterate troughobj
and add all unique elements to the set. Since strings are also iterable, if you pass a string toset()
then you get the unique letters in your set. You can put your obj to a list first:However that is not elegant IMO. You know, even for the creation of an empty dictionary we prefer
{}
overdict()
. Same here. I wolud use the following syntax:Note that for tuples, you need a comma after it:
For Python2.7+:
Example:
Note that an empty
{}
is not aset
, its adict
.Help on
set
: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()
:If the set also isn't likely to change, consider using a
frozenset
: