- How do I create a Python set with only one element?
- 6 Answers 6
- How do I create a Python set with only one element?
- How do I create a Python set with only one element?
- Creating Set of objects of user defined class in python
- Python Sets
- How do I create a Python set with only one element?
- Python Solutions
- Solution 1 — Python
- Solution 2 — Python
- Solution 3 — Python
- Solution 4 — Python
- Solution 5 — Python
- Solution 6 — Python
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)
6 Answers 6
In 2.7 as well as 3.x, you can use:
In general, the expression x, creates a tuple with one element ( x ) — it’s a comma that makes a tuple, not parentheses. x, is the same as (x,) .
For example, this easy way:
>>> myString = 'foobar' >>> s = >>> s set(['foobar']) >>> s = >>> s set(['spam'])
Note that an empty <> is not a set , its a dict .
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'])
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:
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:
Note that for tuples, you need a comma after it:
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 51.7 ns ± 1.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
How do I create a Python set with only one element?
Python3 Output: Removing elements from the Set Using remove() method or discard() method Elements can be removed from the Set by using built-in remove() function but a KeyError arises if element doesn’t exist in the set. Raise KeyError if the set is empty update() Updates a set with the union of itself and others union() Returns the union of sets in a new set difference() Returns the difference of two or more sets as a new set difference_update() Removes all elements of another set from this set discard() Removes an element from set if it is a member.
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 :
In 2.7 as well as 3.x, you can use:
For example, this easy way:
>>> myString = 'foobar' >>> s = >>> s set(['foobar']) >>> s = >>> s set(['spam'])
Note that an empty <> is not a set , its a dict .
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'])
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:
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:
Note that for tuples, you need a comma after it:
List — How to have a set of sets in Python?, With a frozenset, since it is immutable, a hash can be calculated, both preventing unexpected behavior, but also restoring our O (1) lookups. In this case, we can do the following: a = frozenset (range (5)) b = frozenset (range (5, 10)) c = frozenset (range (5)) d = set ( [a, b, c]) Code sample>>> set([frozenset([1,2]), frozenset([2,3])])set([frozenset([1, 2]), frozenset([2, 3])])Feedback
Creating Set of objects of user defined class in python
table = set([]) class GlobeLearningTable(object): def __init__(self,mac,port,dpid): self.mac = mac self.port = port self.dpid = dpid def add(self): global table if self not in table: table.add(self) class LearningSwitch(object): def __init__ (self, connection, transparent): self.connection = connection self.transparent = transparent self.macToPort = <> connection.addListeners(self) self.hold_down_expired = _flood_delay == 0 def _handle_PacketIn (self, event): packet = event.parsed self.macToPort[packet.src] = event.port # 1 packet_src = str(packet.src) packet_mac = packet_src.upper() entry = GlobeLearningTable(packet_mac, event.port, dpid_to_str(self.connection.dpid)) entry.add()
Problem : entry.add() method adds new object every time it is called and increments the items in the table.
This should not happen because
- In the add method I am checking that is that object in the table or not , then I am adding that particular object.
- Table is a set which is unordered list, which should not have duplicate objects.
Help: is there any way in this set u p I can add the object only when it’s not in the table.
You need to implement __eq__ and __hash__ methods to teach Python about how to recognise unique GlobeLearningTable instances.
class GlobeLearningTable(object): def __init__(self,mac,port,dpid): self.mac = mac self.port = port self.dpid = dpid def __hash__(self): return hash((self.mac, self.port, self.dpid)) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return self.mac == other.mac and self.port == other.port and self.dpid == other.dpid
Now your object is comparable, and equal objects will also return equal values for __hash__ . This lets set and dict objects store your objects efficiently and detect if it is already present:
>>> demo = set([GlobeLearningTable('a', 10, 'b')]) >>> GlobeLearningTable('a', 10, 'b') in demo True
Create Ordered Set in Python, To use the OrderedSet class, we have to install the ordered-set package first on our device with the Python package manager. The command to install the ordered-set package is given below. pip install ordered-set Now, we can create a set that preserves the order of each set element. This process is demonstrated in the …
Python Sets
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Creating a Set
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’.
Note – A set cannot have mutable elements like a list or dictionary, as it is mutable.
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 :
Python Solutions
Solution 1 — Python
In 2.7 as well as 3.x, you can use:
Solution 2 — Python
For example, this easy way:
Solution 3 — Python
set_display ::= " (expression_list | comprehension) ">"
>>> myString = 'foobar' >>> s = >>> s set(['foobar']) >>> s = 'spam'> >>> s set(['spam'])
Note that an empty <> is not a set , its a dict .
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:
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:
Note that for tuples, you need a comma after it:
Solution 5 — Python
If the set also isn’t likely to change, consider using a frozenset :
Solution 6 — Python
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)