Master Python data types with this comprehensive guide. Learn about numeric, string, boolean, and collection data types with examples, exercises, and tasks. Perfect for beginners and professionals to enhance their Python programming skills.
In Python, a set is an unordered collection of unique elements, meaning no duplicates are allowed. Sets are useful when you want to store multiple items but donβt need to keep them in a particular order, and you want to ensure that each item only appears once.
You can create a set using curly braces {}
or the set()
function.
# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set using the set() function
my_set = set([1, 2, 3, 4, 5])
# Creating a set
fruits = {"apple", "banana", "cherry", "apple"}
# Displaying the set
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Notice how apple
only appears once, even though we tried to add it twice.
Adding Elements:
Use the add()
method to add an item to a set.
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Removing Elements:
Use remove()
or discard()
to remove an item.
fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry'}
Set Operations: Sets support mathematical operations like union, intersection, and difference.
|
): Combines elements from both sets.&
): Finds common elements between sets.-
): Finds elements in one set but not the other.set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# Difference
print(set1 - set2) # Output: {1, 2}
When the order of elements doesnβt matter.
In Python, a set is an unordered collection of unique elements, meaning no duplicates are allowed. Sets are useful when you want to store multiple items but donβt need to keep them in a particular order, and you want to ensure that each item only appears once.
Creating a Set
You can create a set using curly braces {}
or the set()
function.
# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set using the set() function
my_set = set([1, 2, 3, 4, 5])
# Creating a set
fruits = {"apple", "banana", "cherry", "apple"}
# Displaying the set
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Notice how apple
only appears once, even though we tried to add it twice.
Write a Python program that:
Example Output:
Numbers: {1, 2, 3, 4}
Write a Python program that:
Example Input:
Original List: [1, 2, 2, 3, 3, 4, 5]
Example Output:
Unique Numbers: {1, 2, 3, 4, 5}
Write a Python program that:
Example Input:
Original List: [1, 2, 2, 3, 4, 4, 5]
Expected Output:
Unique Numbers: {1, 2, 3, 4, 5}
Write a Python program that:
Expected Output:
Even Numbers: {2, 4, 6, 8, 10}
Prime Numbers: {2, 3, 5, 7}
Union: {2, 3, 4, 5, 6, 7, 8, 10}
Intersection: {2}