In Python, the set()
function proves to be a versatile tool for efficient collection manipulation. This article delves into its functionality, applications, and significance through detailed examples.
Understanding set() Function
The set()
function in Python is employed to create sets, which are unordered collections of unique elements. Its syntax is straightforward:
set(iterable)
Here, iterable
represents any iterable object, such as lists, tuples, or strings, from which unique elements are extracted to form the set.
Example 1: Creating a Set from a List
my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set(my_list)
print("Set:", my_set)
Output 1:
Set: {1, 2, 3, 4, 5}
Example 2: Creating a Set from a String
my_string = "hello"
my_set = set(my_string)
print("Set:", my_set)
Output 2:
Set: {'h', 'o', 'e', 'l'}
Example 3: Operations on Sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
print("Union:", set1.union(set2))
# Intersection
print("Intersection:", set1.intersection(set2))
# Difference
print("Difference (set1 - set2):", set1 - set2)
print("Difference (set2 - set1):", set2 - set1)
Output 3:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (set1 - set2): {1, 2}
Difference (set2 - set1): {5, 6}
Points to Remember
- Sets in Python are unordered collections of unique elements.
- The
set()
function extracts unique elements from any iterable object. - Sets support various operations such as union, intersection, and difference for efficient data manipulation.