InterviewSolution
| 1. |
Sets in Python |
||||||||||
|
Answer» Initializing Sets: Sets are initialized using curly braces {} or set() in python. A python set is basically an unordered collection of unique values, i.e. it will automatically remove duplicate values from the set. s = {1, 2, 3}print(s) s = set([1, 2, 3]) print(s) s = {1, 2, 3, 3, 2, 4, 5, 5} print(s) Output: {1, 2, 3} {1, 2, 3} {1, 2, 3, 4, 5} Inserting elements in set: We can insert a single element into a set using the add function of sets. s = {1, 2, 3, 3, 2, 4, 5, 5}print(s) # Insert single element s.add(6) print(s) Output: {1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 6} To insert multiple elements into a set, we use the update function and pass a list of elements to be inserted as parameters. s = {1, 2, 3, 3, 2, 4, 5, 5}# Insert multiple elements s.update([6, 7, 8]) print(s) Output: {1, 2, 3, 4, 5, 6, 7, 8} Deleting elements from the set: We can delete elements from a set using either the remove() or the discard() function. s = {1, 2, 3, 3, 2, 4, 5, 5}print(s) # Remove will raise an error if the element is not in the set s.remove(4) print(s) # Discard doesn't raise any errors s.discard(1) print(s) Output: {1, 2, 3, 4, 5} {1, 2, 3, 5} {2, 3, 5} Operators in sets: The below table shows the operators used for sets:
The set operators are represented in the Venn Diagram below: Examples: a = {1, 2, 3, 3, 2, 4, 5, 5}b = {4, 6, 7, 9, 3} # Performs the Intersection of 2 sets and prints them print(a & b) # Performs the Union of 2 sets and prints them print(a | b) # Performs the Difference of 2 sets and prints them print(a - b) # Performs the Symmetric Difference of 2 sets and prints them print(a ^ b) Output: {3, 4} {1, 2, 3, 4, 5, 6, 7, 9} {1, 2, 5} {1, 2, 5, 6, 7, 9} |
|||||||||||