☺️Sets

A set is an unordered collection of unique elements in Python. The elements can be of any data type, but they must be immutable (i.e., they cannot be changed). Sets are mutable, which means that you can add, remove, and update their elements after they have been created.

In Python, sets are defined using curly braces {} or the built-in set() function.

Creating a Set

To create a set, you can define a comma-separated list of elements inside curly braces {} or use the set() function with a list of elements as an argument.

Here's an example of how to create a set:

# Creating a set
fruits = {"apple", "banana", "cherry"}
print(fruits)
# Output: {'banana', 'apple', 'cherry'}

# Creating a set using set() function
colors = set(["red", "green", "blue"])
print(colors)
# Output: {'blue', 'green', 'red'}

As you can see, the elements in a set are not ordered in any particular way.

Create an Empty Set in Python

To create an empty set in Python, you can use either of the following ways:

  1. Using curly braces {}:

my_set = {}
print(type(my_set))   # <class 'dict'>

Here, the empty curly braces {} actually create an empty dictionary instead of an empty set.

  1. Using the set() function:

my_set = set()
print(type(my_set))   # <class 'set'>

Here, we use the set() function to create an empty set.

Note: To create a set with at least one element, we should enclose the elements in curly braces {} or use the set() function.

Duplicate Items in a Set

In a set, duplicate items are not allowed. If we try to add a duplicate item to a set, it will not be added and the set will remain unchanged.

For example:

my_set = {1, 2, 3, 4, 5}
print(my_set)  # Output: {1, 2, 3, 4, 5}

my_set.add(5)
print(my_set)  # Output: {1, 2, 3, 4, 5}

my_set.add(6)
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

In the above example, we try to add the value 5 to the set my_set twice, but it only gets added once. When we try to add the value 6, it gets added to the set since it is not a duplicate item.

Accessing Set Elements

Since sets are unordered, you cannot access their elements by index. Instead, you can loop through the set using a for loop or check if an element is in the set using the in keyword.

Here's an example:

# Looping through a set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)
# Output:
# banana
# apple
# cherry

# Checking if an element is in a set
colors = set(["red", "green", "blue"])
print("red" in colors)
# Output: True

Modifying Sets

You can add, remove, or update elements in a set after it has been created.

Adding Elements to a Set

To add an element to a set, you can use the add() method or the update() method to add multiple elements.

Here's an example:

# Adding an element to a set
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
# Output: {'banana', 'apple', 'cherry', 'orange'}

# Adding multiple elements to a set
colors = set(["red", "green", "blue"])
colors.update(["yellow", "purple"])
print(colors)
# Output: {'red', 'yellow', 'blue', 'purple', 'green'}

Removing Elements from a Set

To remove an element from a set, you can use the remove() method or the discard() method. The only difference between the two methods is that if you try to remove an element that is not in the set, the remove() method will raise a KeyError exception, while the discard() method will not.

Here's an example:

# Removing an element from a set
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
# Output: {'apple', 'cherry'}

# Removing an element that does not exist using remove() method
fruits.remove("orange")
# Output: KeyError: 'orange'

# Removing an element that does not exist using discard() method
fruits.discard("orange")
print(fruits)
# Output: {'apple', 'cherry'}

Updating Elements in a Set

To update an element in a set, you can use the update() method or the add() method.

The update() method is used to add multiple items to a set at once. It takes an iterable as an argument and adds each element of the iterable to the set. If any of the elements already exist in the set, they are ignored.

Here's an example of using the update() method to add multiple elements to a set:

fruits = {'apple', 'banana', 'cherry'}
fruits.update(['orange', 'grape'])
print(fruits)

Output:

{'banana', 'cherry', 'orange', 'grape', 'apple'}

The add() method, on the other hand, is used to add a single element to a set. If the element already exists in the set, it is ignored.

Here's an example of using the add() method to add a single element to a set:

fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
print(fruits)

Output:

{'banana', 'cherry', 'orange', 'apple'}

You can also update a set with another set using the update() method:

fruits1 = {'apple', 'banana', 'cherry'}
fruits2 = {'orange', 'grape', 'apple'}
fruits1.update(fruits2)
print(fruits1)

Output:

{'banana', 'cherry', 'orange', 'grape', 'apple'}

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.

FunctionDescription

len()

Returns the length (number of items) in a set

max()

Returns the maximum value of a set

min()

Returns the minimum value of a set

any()

Returns True if any item in the set is true. If the set is empty, returns False.

all()

Returns True if all items in the set are true. If the set is empty, returns True.

set()

Constructs a new set from an iterable (list, tuple, string, etc.)

sorted()

Returns a new sorted list from the items in a set

sum()

Returns the sum of all elements in a set

pop()

Removes and returns an arbitrary item from the set

clear()

Removes all elements from the set

copy()

Returns a shallow copy of the set

isdisjoint()

Returns True if two sets have no intersection

issubset()

Returns True if all items in the set are present in another set

issuperset()

Returns True if a set contains all the items in another set

union()

Returns a new set with all items from both sets

intersection()

Returns a new set with items common to both sets

difference()

Returns a new set with items in one set but not the other

symmetric_difference()

Returns a new set with items in either set, but not both sets

Iterate Over a Set in Python

You can iterate over a set in Python using a for loop. Here's an example:

fruits = {'apple', 'banana', 'cherry'}

for fruit in fruits:
    print(fruit)

Output:

banana
apple
cherry

Note that the order of the elements in the set may vary when you iterate over it.

Find Number of Set Elements

To find the number of elements in a set in Python, you can use the built-in len() function.

Here's an example:

my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5

In the above example, we have a set my_set with 5 elements. We use the len() function to find the number of elements in the set and print the output, which is 5.

Set Operations

Python Set provides different built-in methods to perform mathematical set operations like union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets in Python can be obtained using the union() method or the pipe operator |. Here's an example:

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

# using union() method
set3 = set1.union(set2)
print(set3)  # Output: {1, 2, 3, 4, 5}

# using pipe operator
set4 = set1 | set2
print(set4)  # Output: {1, 2, 3, 4, 5}

In the above example, we have two sets set1 and set2. We can obtain the union of these two sets by calling the union() method on set1 and passing set2 as an argument. We can also use the pipe operator | to perform the union operation on these two sets. The result of both approaches is the same set {1, 2, 3, 4, 5}.

Set Intersection

Set Intersection means the common elements in both sets.

In Python, the intersection of two sets can be found using the intersection() method or the & operator.

Here's an example:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# using intersection() method
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {4, 5}

# using & operator
intersection_set = set1 & set2
print(intersection_set)  # Output: {4, 5}

In the above example, we have two sets, set1 and set2, and we are finding their intersection using the intersection() method and the & operator. The resulting set contains the common elements in both sets, which are 4 and 5.

Check if two sets are equal

The sets are equal

Output:

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

if set1 == set2:
    print("The sets are equal")
else:
    print("The sets are not equal")

To check if two sets are equal, you can use the == operator. Here's an example:

Other Python Set Methods

Here are some other commonly used methods in Python sets:

  1. add(element): Adds an element to the set.

  2. remove(element): Removes an element from the set. Raises a KeyError if the element is not found.

  3. discard(element): Removes an element from the set. Does not raise an error if the element is not found.

  4. pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.

  5. clear(): Removes all elements from the set.

  6. copy(): Returns a copy of the set.

  7. intersection_update(other_set): Updates the set with the intersection of itself and another set.

  8. difference_update(other_set): Updates the set with the difference of itself and another set.

  9. symmetric_difference_update(other_set): Updates the set with the symmetric difference of itself and another set.

  10. update(other_set): Updates the set by adding elements from another set.

These methods modify the set in place and do not return a new set.

Last updated