Python Set
A set in Python is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values and do not maintain order. They are highly useful when you need to ensure that only unique items are stored, and they support operations like union, intersection, and difference. Sets are determined by curly brackets { }
Example:
# Examples of set in Python
set1 = {} # An empty set
set2 = {4, 5, 1, 7, 3} # A set with 5 integers
set3 = {1, ‘XYZ’, True} # In Python, different types of values can be stored in a set
Explanation:
● set1 = { }: This is an empty set that doesn’t contain any elements.
● set2 = {4, 5, 1, 7, 3}: This set contains 5 integer values: 4, 5, 1, 7, and 3.
● set3 = {1, ‘XYZ, ‘True’}: This set contains 3 values of distinct data types. In python it is possible to store different types of values.
Set Operations
1. Union: Combines elements from two sets, removing duplicates.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
2. Intersection: Returns elements common to both sets.
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
3. Difference: Returns elements present in the first set but not in the second.
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
4. Symmetric Difference: Returns elements in either set, but not in both.
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
Course Video
Course Video English:
Task
1. Integer set:
Create a set of integers with values from 1 to 5.
Print all elements of the set.
2. String set:
Create a set of strings with the names of three fruits.
Print all elements of the set.
3. Double set:
Create a set of doubles with any 4 double values.
Print the sum of all elements in the set.
4. Boolean set:
Create a set of booleans with alternating true and false values.
Print all elements of the set.
Task Video
YouTube Reference :
There is only one type, the set data structure.
Unordered collections of unIque items.
HashSet stores unIque elements and is unordered, while lists allow duplicates and are ordered.
No, sets are unordered.
Use curly braces {} or the set() function.
Sets are efficient for membership testing and eliminating duplicates.
Include union, intersection, difference, and symmetric difference.
There is only one type, the set data structure.
Methods like add(), remove(), and discard().
__call__ methods in Python: Special methods that allow an object to be called as a function.