A set is an unordered collection of unique elements as opposed to lists in which elements are ordered and need not be unique. Sets are useful when you want to store a collection of items without any duplicates and don't require the elements to be in a specific order.

To create a set, you can use curly braces {} or the set() function. Here's an example:

fruits = {"apple", "banana", "orange"}

In this code, we create a set called fruits that contains three elements: "apple", "banana", and "orange". Note that the order of the elements may vary when printed because sets are unordered.

Sets have several useful properties and methods. Let's explore some of them with practical examples:

Adding and Removing Elements

You can add elements to a set using the add() method and remove elements using the remove() method. Here's an example:

fruits = {"apple", "banana", "orange"}
print(fruits)  # Output: {"apple", "orange", "kiwi"}

In this code, we add the element "kiwi" to the fruits set using the add() method. We then remove the element "banana" using the remove() method. The resulting set contains "apple", "orange", and "kiwi".

Checking Membership

You can check if an element is present in a set using the in keyword. Here's an example:

fruits = {"apple", "banana", "orange"}
print("banana" in fruits)  # Output: True
print("kiwi" in fruits)  # Output: False

In this code, we check if the elements "banana" and "kiwi" are present in the fruits set. The in keyword returns True if the element is present and False otherwise.

Set Operations

Sets support various mathematical set operations, such as union, intersection, and difference. Here's an example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)

print(union)  # Output: {1, 2, 3, 4, 5}
print(intersection)  # Output: {3}
print(difference)  # Output: {1, 2}

In this code, we perform set operations on set1 and set2. The union() method returns a set containing all the unique elements from both sets. The intersection() method returns a set containing the common elements. The difference() method returns a set containing the elements that are in set1 but not in set2.

Sets provide a convenient way to work with collections of unique elements and perform set operations efficiently.