Frozen Sets Frozen Sets are immutable objects that only support methods and operators that produce results without affecting the frozen set or sets to which they apply.
|
Exit:
Normal Set set ([’a’,’ c’, ’b’,’ d’]) Frozen Set frozenset ([’e’,’ g’, ’ f’])
1. Add (x) method: adds an x element to install if it is not already in the set.
people = {"Jay", "Idrish", "Archil"} people.add ( "Daxit")
-" This will add Daxit to the set of people.
2. union (s) : Returns the union of two sets. Using & # 39; | & # 39; The operator between 2 sets is the same as writing set1.union (set2)
people = {"Jay", "Idrish", "Archil"} vampires = {"Karan", "Arjun"} population = people.union (vampires)
OR
population = people | vampires
-" The population set will have both human and vampire components
3. The intersect (s): method returns the intersection of two sets. The & # 39; & amp; & # 39; operator can also be used in this case.
victims = people.intersection (vampires)
-" The set of victims will contain a common element of humans and vampires
4. Difference method (s): Returns a set containing all the elements of the calling set, but not the second set. We can use the "-" operator here.
safe = people.difference (vampires)
OR
safe = people - vampires
-" The safe will contain all the elements that humans have, but not vampires.
5. clear () Method: clears the entire set.
victims.clear ()
-" Cleans up a collection of victims
However, Python collections have two main pitfalls:
- Collection does not support elements in any particular order.
- Only instances of immutable types can be added to the Python collection.
Sets and frozen sets support the following operators :
enter s # content validation
key not in s # non-save validation
s1 == s2 # s1 is equivalent to s2
s1 ! = s2 # s1 is not equivalent to s2
s1 = s2 # s1 is a superset of s2
s1" s2 # s1 — correct superset of s2
s1 | s2 # combining s1 and s2
s1 & amp; s2 # intersection of s1 and s2
s1 — s2 # a set of elements in s1, but not s2
s1 ˆ s2 # a set of elements in exactly one of s1 or s2
A code snippet to illustrate all Set operations in Python
|
Exit:
(’Set1 =’, set ([1, 2, 3, 4, 5])) (’Set2 =’, set ([3, 4, 5, 6, 7])) (’Union of Set1 & amp; Set2: Set3 = ’, set ([1, 2, 3, 4, 5, 6, 7])) (’ Intersection of Set1 & amp; Set2: Set4 = ’, set ([3, 4, 5])) Set3 is superset of Set4 Set4 is subset of Set3 (’Elements in Set3 and not in Set4: Set5 =’, set ([1, 2, 6, 7])) Set4 and Set5 have nothing in common After applying clear on sets Set5: (’Set5 =’, set ([]))