Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 836
Thalecress Avatar asked Nov 14 '13 18:11

Thalecress


People also ask

How do you create a set with one element in Python?

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.).

Which function allows a single element in set?

The add() method adds a given element to a set.

How do you make an empty set in Python?

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'> ”.

Can you slice a set in Python?

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.


1 Answers

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

mySet = {'abc'} 
like image 149
dstromberg Avatar answered Sep 19 '22 08:09

dstromberg