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)
Creating Python Sets A set is created by placing all the items (elements) inside curly braces {} , separated by comma, or by using the built-in set() function. It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
The add() method adds a given element to a set.
To create an empty set in python we have to use the set() function without any arguments, if we will use empty curly braces ” {} ” then we will get an empty dictionary. After writing the above code (create an empty set in python), Ones you will print “type(x)” then the output will appear as a “ <class 'set'> ”.
For example, sets can't be indexed or sliced. However, Python provides a whole host of operations on set objects that generally mimic the operations that are defined for mathematical sets.
In 2.7 as well as 3.x, you can use:
mySet = {'abc'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With