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.
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}