- Are unordered like dictionaries.
- only Unique values are allowed
- Supports set operations like Union and Intersect.
Sets
Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set function. They share some functionality with lists, such as the use of in to check whether they contain a particular item.
num_set = {1, 2, 3, 4, 5}
word_set = set(["spam", "eggs", "sausage"])
print(3 in num_set)
print("spam" not in word_set)
Result:>>>
True
False
>>>
To create an empty set, you must use set(), as {} creates an empty dictionary.
Use discard to remove an element from a set - if element is not found it will do nothing.
num_set.discard(1)
Use remove to remove an element from a set - if the element is not found it will throw an error
num_set.remove(1)
Set Union and Intersection method to find Unique items in 2 groups or common items in tow groups.
num_set.union(someOtherSet)
num_set.Intersection(someOtherSet)
or instead of Union or Intersect we can use & or | operators
Comments
Post a Comment