Sets in Python

Mannan Ul Haq
0

In Python, a set is a collection of unordered and unindexed items, all of which are unique. Sets in Python are a very useful and versatile data type that are often used for tasks such as eliminating duplicate entries from a list, performing mathematical operations such as intersection, union, and difference, or testing for membership. Sets are denoted by enclosing comma-separated items in curly brackets '{}'.


Key properties of Python sets are:

1. Unordered: Sets in Python are unordered collections, meaning that the elements don't have a specific order. The order in which elements are added to the set is not necessarily the order in which they are stored or retrieved.

2. Does Not Allows Duplicate Members: Sets in Python do not contain duplicate elements. That is, each value can appear at most once in a set. If you try to add a duplicate element to a set, it simply ignores the action and leaves the set unchanged.

3. Unindexed: Sets are unindexed, which means you cannot access items in a set by referring to an index.

4. Mutable: Although you cannot change or replace items of a set, you can add new items to it or remove items from it.



Creating Sets:

To create a set in Python, you simply enclose the elements you want to include within curly brackets '{}', separated by commas.


# Examples of creating sets
numbers = {1, 2, 3, 4, 5}  # A set of integers
names = {"Alice", "Bob", "Charlie"}  # A set of strings
mixed = {1, "Alice", True}  # A set with mixed data types


Using set() Constructor:

Python also provides the 'set()' constructor, which you can use to create a set from an existing iterable object such as a string, list, tuple, or another set.


# Using set() constructor with a string
str_set = set("Hello")
print(str_set)  # Outputs: {'e', 'o', 'H', 'l'}

# Using set() constructor with a list
list_set = set([1, 2, 3, 4])
print(list_set)  # Outputs: {1, 2, 3, 4}


Note that the 'set()' constructor creates a set without any elements when called without arguments.


empty_set = set()
print(empty_set)  # Outputs: set()



Set Length:

In Python, the `len()` function is used to get the number of items (length) of a set.


Here is an example:


numbers = {1, 2, 3, 4, 5}
length = len(numbers)
print(length)  # Outputs: 5



Check Items:

Since sets are unordered and unindexed, you cannot access individual items in a set using an index or a key. Instead, you can check if an item exists in a set using the 'in' keyword.

Here's an example:

fruits = {"apple", "banana", "cherry"}
if "apple" in fruits:
    print("Yes, 'apple' is in the fruits set")  # This will be printed


Add Items:

Python provides methods to add items to a set, whether you want to add a single item or multiple items.

The 'add()' method is used to add a single item to a set.

Here's an example:

fruits = {"apple", "banana", "cherry"}
fruits.add("date")
print(fruits)  # Outputs: {'apple', 'date', 'banana', 'cherry'}

In this example, the string "date" is added to the 'fruits' set.

If you want to add more than one item to a set, you can use the 'update()' method, which takes an iterable (like a list, tuple, or string) as an argument.

fruits = {"apple", "banana", "cherry"}
fruits.update({"date", "elderberry"})
print(fruits)  # Outputs: {'elderberry', 'apple', 'date', 'banana', 'cherry'}

In the above example, 'update()' adds the elements of the list '["date", "elderberry"]' to the 'fruits' set. The 'update()' method treats the argument as a collection of individual elements, unlike the 'add()' method, which would add the list as a single item.


Remove Items:

In Python, sets provide several methods for removing items. Here is an overview of the main methods:

1. 'remove(item)': This method removes the specified item from the set. If the item does not exist in the set, it raises a KeyError.

fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # Outputs: {'apple', 'cherry'}
# If you try to remove an item that does not exist, you will get a KeyError:
# fruits.remove("orange")  # Raises KeyError: 'orange'


2. 'discard(item)': This method also removes the specified item from the set, but unlike 'remove()', it does not raise an error if the item does not exist.

fruits = {"apple", "banana", "cherry"}
fruits.discard("cherry")
print(fruits)  # Outputs: {'apple', 'banana'}
# You can discard an item that does not exist without getting an error:
fruits.discard("orange")  # Does nothing


3. 'pop()': This method removes and returns an arbitrary item from the set. Sets are unordered, so you cannot predict which item will be popped. If the set is empty, 'pop()' raises a KeyError.

fruits = {"apple", "banana", "cherry"}
popped = fruits.pop()
print(popped)  # Outputs an arbitrary item from the set
print(fruits)  # Outputs the remaining set
# If the set is empty, you will get a KeyError:
# empty_set = set()
# empty_set.pop()  # Raises KeyError: 'pop from an empty set'


4. 'clear()': This method removes all items from the set, leaving it empty.

fruits = { "apple", "banana", "cherry" }
fruits.clear()
print(fruits)  # Outputs: set()

5. 'del set': This statement removes the set completely. After running this command, the set and its name no longer exist.

fruits = { "apple", "banana", "cherry" }
del fruits
# If you try to print the set after deleting it, you will get a NameError :
# print(fruits)  # Raises NameError : name 'fruits' is not defined


Set Operations:

In Python, sets support various set operations that allow you to manipulate and combine sets in different ways. Keep in mind that sets are unordered collections of unique elements. Additionally, in sets, the values 'True' and '1' are considered the same value and are treated as duplicates.

Here are some common set operations:

1. Union:

The union of two sets contains all unique elements from both sets. You can use the 'union()' method to perform the union operation.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.union(set2)  # Using the union() method
print(result)  # Outputs: {1, 2, 3, 4, 5}

The 'update()' method adds elements from another set (or any iterable) to the current set, effectively performing a union in-place.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.update(set2)  # Using the update() method
print(set1)  # Outputs: {1, 2, 3, 4, 5}


2. Intersection:

The intersection of two sets contains elements that are present in both sets. You can use the 'intersection()' method perform the intersection operation.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.intersection(set2)  # Using the intersection() method
print(result)  # Outputs: {3}

The 'intersection_update()' method updates the current set to contain only the elements that are present in both sets, effectively performing the intersection in-place.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.intersection_update(set2)  # Using the intersection_update() method
print(set1)  # Outputs: {3}


3. Symmetric Difference:

The symmetric difference of two sets contains elements that are present in either of the sets but not in both. You can use the 'symmetric_difference()' method to perform the symmetric difference operation.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
result = set1.symmetric_difference(set2)  # Using the symmetric_difference() method
print(result)  # Outputs: {1, 2, 4, 5}

The 'symmetric_difference_update()' method updates the current set to contain only the elements that are present in either of the sets but not in both, effectively performing the symmetric difference in-place.

set1 = { 1, 2, 3 }
set2 = { 3, 4, 5 }
set1.symmetric_difference_update(set2)  # Using the symmetric_difference_update() method
print(set1)  # Outputs: {1, 2, 4, 5}

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !