Python Sets
Python Sets

A Python sets is a data structure in Python that allows you to store a collection of elements. Python sets are similar to lists, but they have a few key differences.

A Python set is a data structure in Python that allows you to store a collection of elements.

In Python, a sets is an unordered collection of unique elements. It is used to store multiple items, but unlike a lists or tuples, a sets does not allow duplicate values. Each element in a set is distinct, making sets useful when you want to work with a collection of items without worrying about duplicates.

Table of Contents

How to Create Sets in Python

You can create a sets in Python using either curly braces {} or the set() constructor.

Create Sets Using Curly Braces {}

This Example shows you how to create the sets using the curly braces {}.

Example:


# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)

Output:


{1, 2, 3, 4, 5}

Create Sets Using the set() Constructor

This Example shows you how to create the sets using the set() Constructor.

Example:


# Creating a set using the set() constructor
my_set1 = set([1, 2, 3, 4, 5])
my_set2 = set((1, 2, 3, 4, 5, 6))

print(my_set1)
print(my_set2)

Output:


{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}

In the above example, I have successfully created two sets, my_set1 and my_set2, using both a list (using square brackets []) and a tuple (using parentheses ()) as input to the set() constructor, and you printed the sets to verify their contents.

Create Empty Set

Keep in mind that if you want to create an empty set, you must use the set() constructor because using empty curly braces {} would create an empty dictionary. See the following example which shows how to create an empty set:

Example:


# Creating an empty set using the set() constructor
empty_set1 = set()
print(empty_set1)

# Creating an empty set using the using empty curly braces {} would create an empty dictionary
empty_set2 = {}
print(empty_set2)
print(type(empty_set2))

Output:


set()
{}
<class 'dict'>

Characteristics of Set Items

Python sets are similar to lists, but they have a few key differences. Which means sets in Python have some specific characteristics that distinguish them from other data structures. The main characteristics of set items are unordered, unique, and do not accept duplicate items. Here we explore these characteristics with examples:

Unordered

Sets are unordered which means they do not maintain any defined order of elements. When you iterate over a set, or try to use, the elements may appear in a different order than when they were added.

Sets in Python are unindexed, which means you cannot access individual elements in a set using indices as you would with a list or tuple. Since sets are unordered collections of unique elements, there is no concept of indexing because there is no specific order in which the elements are stored.

The lack of indexing is a fundamental characteristic of sets in Python, and it distinguishes them from other data structures like lists and tuples, which allow for indexing and maintain a specific order of elements.

Example:


my_set1 = {3, 1, 2, 4, 7, 8, 5, 6}
print(my_set1)  

my_set2 = {"Yellow", 1, "Blue", "Green", 3, "Red", "Black", 4, "White"}
print(my_set2)  

Output:


{1, 2, 3, 4, 5, 6, 7, 8}
{'Red', 'Green', 'Black', 3, 1, 4, 'White', 'Blue', 'Yellow'}

The output in the above example shows the items stored in the my_set1 variable was sorted in ascending order, but why are python these numerical values in the sets are ordered in ascending order?

Although we said the sets are unordered, these behavior you’re observing where the set appears to be sorted in ascending order is due to an implementation detail in Python. While it’s true that sets are unordered, starting from Python 3.6 and onwards, the implementation of Python’s built-in set type does maintain an internal order of elements for performance reasons. This internal order may sometimes coincide with the natural ordering of elements, making it appear sorted.

However, this behavior is not guaranteed and should not be relied upon in your code. In practice, you should always treat sets as unordered collections because the internal ordering can change between different versions of Python or implementations. Python’s official documentation explicitly states that sets are unordered collections of unique elements.

So, even though the elements in your set may appear sorted in this specific case, you should not rely on this behavior for correctness in your code. Always use sets for their primary purpose, which is to store unique elements, without making assumptions about their order.

Unique Elements

Sets ensure that each element is unique. If you try to add a duplicate element to a set, it will not be added, and the set will remain unchanged.

This characteristic is what makes sets useful for eliminating duplicates from a collection.

Example:


my_set = {1, 2, 2, 3, 3, 1, 4, 5, 5, 7, 8, 7}
print(my_set) 

Output:


{1, 2, 3, 4, 5, 7, 8}

Immutable

Unlike lists, sets are immutable or unchangeable, which means that once you create a set, you cannot change its individual elements. However, you can add or remove elements from a set.

Try to mutate or change the immutable or unchangeable Set Items:

Example:


my_set = {1, 2, 3}
# Attempting to change the first element to 4
my_set[0] = 4  
print(my_set)

Output:


Traceback (most recent call last):
  File "/Users/Sets.py", line 83, in <module>
    my_set[0] = 4  # Attempting to change the first element to 4
TypeError: 'set' object does not support item assignment

Try to add or remove elements from a set:

Example:


my_set = {1, 2, 3, 7, 8, 9}
# Adding a duplicate element
my_set.add(2)  
print(my_set)  
# Adding a non-duplicate element
my_set.add(5)  
print(my_set)  

# Remove Sets Items Using remove Method
my_set.remove(3)
print(my_set)

Output:


{1, 2, 3, 7, 8, 9}
{1, 2, 3, 5, 7, 8, 9}
{1, 2, 5, 7, 8, 9}

Store Different Data Types in Sets

Sets in Python can store elements of different data types. Unlike some other programming languages, Python sets allow you to mix and match different data types within the same set. Here is how to do such claim in practice:

Example:


my_set = {1, 'Akesh', 3.14, True, (4, 5), False}
print(my_set)

Output:


{False, 1, (4, 5), 3.14, 'Akesh'}

In the above example shows that my_set set variable contains elements of various data types, including an integer, a string, a float, boolean (or bool) and a tuple. Sets maintain the uniqueness of elements, so even though there are different data types, duplicate values are not allowed.

Note: In the context of sets, True and 1 are considered duplicates because they have the same “truthy” value. In Python, True is equal to 1, and False is equal to 0 when used in numerical comparisons. This way the true value was not produced during the output.

Check Sets Type

In order to check the data type of a set in Python, you can use the type() function. See the following demonstrations.

Example:


my_set = {1, 'Ali', 3.14, True, (4, 5), False}
print(type(my_set))

Output:


<class 'set'>

Check Sets Length

You can find the length (number of elements) of a set using the len() function. Here is a practice example about this:

Example:


my_set1 = {1, 2, 3, 4, 5}
set_length = len(my_set1)
print(set_length)

my_set2 = {1, 2, 6, 33, 3, 4, 5, "Flash", True}
print(my_set2) # the True will not be displayed because 1 and True is same so it will considered duplicate
print(len(my_set2))

# Without Duplicate
my_set3 = {44, 2, 6, 33, 3, 4, 5, "Flash", True}
print(my_set3)
print(len(my_set3))

Output:


{1, 2, 3, 4, 33, 6, 5, 'Flash'}
8
{33, 2, 3, 4, 5, 6, True, 44, 'Flash'}
9

Access Sets Items

In Python sets, you cannot access elements using traditional indexing because sets are unordered collections of unique elements. However, you can iterate over the items in a set using a loop or check for the existence of a specific item using membership operators (in and not in).

Access Sets Items Using if and Membership Operators

The following example shows how we can access set items using membership operators:

Example:


my_set = {1, 2, 3, 4, 5, 6, 7, 8}
if 7 in my_set:
    print("7 is in the set")
if 5 not in my_set:
    print("5 is not in the set")
if 10 not in my_set:
    print("10 is not in the set")

Output:


7 is in the set
10 is not in the set

Access Sets Items Using Loops

The following is another example shows how we can access set items using loops:

Example:


# Create a set
my_set = {44, 2, 6, 33, 3, 4, 5, "Flash", True}

# Access set items using a for loop
print("Accessing set items using a for loop:")
for item in my_set:
    print(item)

Output:


33
2
3
4
5
6
True
Flash
44

Can we Index Set Items

As mentioned earlier, sets do not support indexing like lists or tuples because they are unordered collections or slicing requires a defined order of elements and this does not exist in Sets. Therefore, there is no concept of positive indexing, negative indexing, positive range indexing or negative range indexing, in sets.

The following example we try and show how such practice will lead an error:

Example:


my_set = {44, 2, 6, 33, 3, 4, 5, "Flash", True}

print(my_set[0:2])

Output:


Traceback (most recent call last):
  File "/Users/Sets.py", line 147, in <module>
    print(my_set[0:2])
TypeError: 'set' object is not subscriptable

In short, sets in Python are unordered collections of unique elements, and they do not support indexing, slicing, or range indexing. You access set items using membership operators or by iterating over the set. If you need ordered access to elements, you should consider using a list or tuple instead.

Change Sets Items

Sets in Python are inherently unordered and do not support direct item assignment or indexing like lists or tuples. This means you cannot change individual elements within a set using indexing or slicing as you would with other data structures.

Example:


my_set = {44, 2, 6, 33, 3, 4, 5, "Flash", True}

my_set[4] = 55
print(my_set)

Output:


Traceback (most recent call last):
  File "/Users/Sets.py", line 147, in <module>
    my_set[4] = 55
TypeError: 'set' object does not support item assignment

This error message in the above shows that sets are immutable, and you cannot change individual elements using indexing and assignment. If you need to modify a set, you should use set methods like add, remove, or discard, which allow you to change the set as a whole by adding or removing elements.

Add New Items to a Set

In this case, if we need to add a new item in a set, we can use the add method to add new items to the set. If the item already exists in the set, it won’t be added again.

Example:


my_set = {1, 2, 3, 5, 7, 8}
my_set.add(4)  # Adding 4 to the set
print(my_set)

Output:


{1, 2, 3, 4, 5, 7, 8}

Add Multiple Items to a Set

The update method allows you to add multiple items to a set by providing an iterable (e.g., a list or another set).

Example:


my_set = {1, 2, 3, 5, 7, 8}
my_set.update([4, 6, 9])  # Adding multiple items to the set
print(my_set)

Output:


{1, 2, 3, 4, 5, 6, 7, 8, 9}

Remove Items From a Set

These methods are used to remove items from a set. remove raises a KeyError if the item is not found, while discard does not raise an error. Not only that we can also use the pop method which removes and returns an arbitrary element from the set. Note: that sets are unordered, so which item gets removed is not deterministic.

Example:


my_set = {1, 2, 3, 5, 7, 8}
my_set.remove(3)  # Removing 3 from the set
print(my_set)

my_set.discard(5)  # Attempting to remove 5, which does exist in the set
print(my_set)

popped_item = my_set.pop()  # Removing and returning an arbitrary item
print("Popped item:", popped_item)
print(my_set)

Output:


{1, 2, 5, 7, 8}
{1, 2, 7, 8}
Popped item: 1
{2, 7, 8}

Delete Entire Sets Items Using del Statement

You can use the del statement to remove the entire set or delete a specific set.

Example:


my_set = {1, 2, 3, 4, 5}
del my_set  # Deleting the entire set
# Now, my_set no longer exists
print(my_set)

Output:


Traceback (most recent call last):
  File "/Users/Sets.py", line 174, in <module>
    print(my_set)
NameError: name 'my_set' is not defined

Unpack Sets

In Python, sets contain multiple items, this process is called packed which means we took multiple values or elements and combine them into a single data structure.

On the other hand, “unpacking sets” refers to the process of extracting the elements stored in a set and assigning them to individual variables.

Unpacking sets can be useful especially when you want to work with the individual elements of a set in your code.

NOTE: sets are unordered collections, so there is no inherent order to the elements. When unpacking a set, you’ll typically get the elements in an arbitrary order.

You can unpack a set by using the assignment operator (=) and assigning the elements to variables. The following demonstration shows how to do set unpacking.

Example:


my_set = {1, 9, 4, 5, "Flash"}
a, b, c, d, e = my_set
print(a, b, c, d, e)

Output:


1 4 5 9 Flash

Unpacking using Asterisk (*)

You can use the asterisk (*) operator to capture multiple elements from the set and store them into a single variable. This process is helpful especially when the number of elements is unknown or variable. The following example shows exactly that.

Example:


my_set = {1, 9, 4, 5, "Flash"}
first, *rest = my_set
print("First:", first)
print("Rest:", rest)

Output:


First: 1
Rest: [4, 5, 'Flash', 9]

The example provided in the above shows unpacking the first element into the variable named first, and the remaining elements are captured into a list assigned to the variable named rest.

Ignoring Elements

There are cases where you’re not interested in certain elements, then you can use an underscore (_) to ignore them during unpacking. See the following example:

Example:


my_set = {1, 9, 4, 5, "Flash"}
first, _, third, *remaining = my_set
print("First:", first)
print("Third:", third)
print("Remaining:", remaining)

Output:


First: 1
Third: 4
Remaining: [5, 9]

The above example, we have ignored the second element using _ and store the remaining elements a variable called remaining list.

Looping Through Set Items in Python

What is set looping: Looping through sets in Python will allow you to iterate over the elements of a set and perform actions on each element. Since we know Sets are unordered collections of unique elements, therefore, looping through them doesn’t guarantee a specific order.

In this case, Python provides several ways that we can loop through sets, including for loops, while loops, and set comprehension.

In this section, I will show you examples and explanations of how to do such tasks.

Using a Simple for Loop

A for loop is the best way and most common way to iterate through a set. You can use the for loop to access each element in the set one by one.

Note: sets are unordered, the order in which elements are traversed may vary.

Example:


my_set = {1, 2, 3, 4, 6, 8, 9}

for item in my_set:
    print("Item: ", item)

Output:


Item:  1
Item:  2
Item:  3
Item:  4
Item:  6
Item:  8
Item:  9

Using a while Loop

Similar to the above, you can also use a while loop to iterate through a set.

Note: you cannot directly access elements in a set using indexing like my_set[i] because sets are unordered collections in Python, and they do not support indexing. Therefore we convert them into a list as shown below.

The while loop will continue until there are no more elements in the set.

Example:


my_set = {1, 2, 3, 4, 6, 8, 9}
# Initialize i to 0 to start at the first index
i = 0
# Use a while loop to iterate through the set
while i < len(my_set):
    # Convert the set to a list to access elements by index
    item = list(my_set)[i]
    print("The item in the set is:", item)
    i = i + 1 

Output:


The item in the set is: 1
The item in the set is: 2
The item in the set is: 3
The item in the set is: 4
The item in the set is: 6
The item in the set is: 8
The item in the set is: 9

Reversing and Pring the items in the Set

This code will use the while loop, similar to the above code but it will print the values in a reverse manner.

Example:


my_set = {1, 2, 3, 4, 6, 8, 9}

# Initialize i to the length of the set minus 1
i = len(my_set) - 1

# Use a while loop to iterate through the set
while i >= 0:
    print("The item at index", i, "is:", list(my_set)[i])
    i = i - 1 

Output:


The item at index 6 is: 9
The item at index 5 is: 8
The item at index 4 is: 6
The item at index 3 is: 4
The item at index 2 is: 3
The item at index 1 is: 2
The item at index 0 is: 1

Identifying and Printing Odd Numbers in a Set Using a while Loop

In this section, I will show you another useful example that aims to iterate through a set named, identify, and print the elements within the set that are odd numbers (i.e., numbers that have a remainder of 1 when divided by 2). Here is the code and its output:

Example:


my_set = {1, 2, 3, 4, 6, 8, 9}
i = 0
while i < len(my_set):
    if list(my_set)[i] % 2:
        print("The item at index", i, "is:", list(my_set)[i])
    i = i + 1 

Output:


The item at index 0 is: 1
The item at index 2 is: 3
The item at index 6 is: 9

Sets comprehension

Sets comprehension is a concise way to create sets in Python by specifying the set's elements and optionally applying an expression to each element. It offers benefits such as readability, brevity, and a straightforward syntax for creating sets based on existing data or conditions.

Syntax: {expression for element in iterable}

In sets comprehension, you define an expression to generate elements, and then you specify an iterable (e.g., a list, tuple, or range) from which elements are extracted. The expression is applied to each element in the iterable, and the resulting values are collected into a new set.

Example:


numbers = {1, 2, 3, 4, 5}
squared_numbers = {x**2 for x in numbers}
print("Squaroot values: ", squared_numbers)

#Another Example

numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
even_numbers = {x for x in numbers if x % 2 == 0}
print("Even numbers:", even_numbers)

Output:


Squaroot values:  {1, 4, 9, 16, 25}
Even numbers: {8, 2, 4, 6}

Sets Comprehension Benefits and Usages

  1. Conciseness: Sets comprehension provides a concise way to generate sets without the need for explicit loops or appending elements one by one.
  2. Readability: Sets comprehension is easy to read and understand, making your code more expressive and compact.
  3. Filtering: You can use conditional expressions to filter elements from an iterable based on specific conditions.

Transformation of Words with Sets Comprehension

The following code is a set comprehension code that aims to transform each word in words variable to uppercase. Take this code and practice.

Example:


words = {"Computer", "Super Computer", "Mini Computer"}
uppercase_words = {word.upper() for word in words}
print(uppercase_words) 

Output:


{'COMPUTER', 'MINI COMPUTER', 'SUPER COMPUTER'}

Set Operations with Sets Comprehension

In Python Set Operations: we can use the Sets comprehension in order to perform set operations such as union, intersection, and difference. Check the following examples we have drafted for you.

Example:


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

union_set = {x for x in set1} | {x for x in set2}
intersection_set = {x for x in set1} & {x for x in set2}
difference_set = {x for x in set1} - {x for x in set2}

print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference:", difference_set)

Output:


Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}

Sets Methods in Python

First of all, what is Set methods: They are built-in functions in Python that can be applied to sets in order to perform various operations and manipulations on set objects.

This section is dedicated to discussing with examples, several important set methods found in Python.

Note: Some of these methods were used in the above sections as well.

Set Method add()

The add() method in Python is used to add a specified element to a set.

If the element is already present, it doesn't duplicate it. Because sets ensure that each element in the set is unique. 

Example:


my_set_1 = {1, 2, 3, 4}
my_set_1.add(5)
print(my_set_1)

# Duplicate will not be uccepted
my_set_2 = {1, 2, 3, 4}
my_set_2.add(4)
print(my_set_2)

Output:


{1, 2, 3, 4, 5}
{1, 2, 3, 4}

Set Method remove()

The remove() method is another built-in set method that removes a specified element from a set.

If the element to be removed is not found, it will trigger a KeyError.

Example:


my_set_1 = {1, 2, 3, 4}
if 2 in my_set_1:
    removed_num = 2
    my_set_1.remove(2)
    print(
        "The reomved number is:", removed_num, "Thus the remained value is:", my_set_1
    )
else:
    removed_num = None

Output:


The reomved number is: 2 Thus the remained value is: {1, 3, 4}

The following example shows removing a missing value. We expect a KeyError to happen.

Example:


my_set_1 = {1, 2, 3, 4}
my_set_1.remove(5)
print("Thus the remained value is:", my_set_1)

Output:


Traceback (most recent call last):
  File "e:\python\set-conti.py", line 99, in <module>
    removed_num = my_set_1.remove(5)
                  ^^^^^^^^^^^^^^^^^^
KeyError: 5

Set Method discard()

The discard() method is used to remove a specified element from a set only if it exists.

If the element is not found in the set, it doesn't raise an error.

Example:


my_set = {1, 2, 3, 4, 5, 6}

# Discard and store the element 2
if 2 in my_set:
    discarded_num = 2
    my_set.discard(2)
else:
    discarded_num = None

print("The discarded number is:", discarded_num, "and the remaining set is:", my_set)

# Attempt to discard 10 (which is not in the set)
if 10 in my_set:
    discarded_num = 10
    my_set.discard(10)
else:
    discarded_num = None

print("The discarded number is:", discarded_num, "and the remaining set is:", my_set)
 

Output:


The discarded number is: 2 and the remaining set is: {1, 3, 4, 5, 6}
The discarded number is: None and the remaining set is: {1, 3, 4, 5, 6}

Set Method pop()

The pop() method is intended to remove and return an arbitrary element from the set.

Although sets are unordered, the element removed is not guaranteed to be the same each time.

Example:


my_set = {1, 2, 3, 4}
popped_element = my_set.pop()
print("You have removed item:", popped_element, "and the rest is: ", my_set)

Output:


You have removed item: 1 and the rest is:  {2, 3, 4}

Set Method clear()

This is one of the popular methods in set. Theclear() method is used to remove all elements from a set, eventually making it empty. Let me show how possible is that.

Example:


my_set = {1, 2, 3, 4}
my_set.clear()
print("The set is cleared:", my_set)

Output:


The set is cleared: set()

Set Method union()

The union() method is a built-in method that returns a new set containing all unique elements from two or more sets. This basically Join Sets. Let me show you an example of that.

Example:


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

union_set = set1.union(set2)
print(union_set)

# Combine more set items
set3 = {6, 7, 8}
union_set = set1.union(set2, set3)
print(union_set)

Output:


{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}

Other Ways to Perform Union Operation Between Sets in Python Using the Pipe Operator (|)

In Python, we can use the | operator in order to perform a union operation (Join Sets) between sets, this basically combines elements from multiple sets into a new set.

Remember, the duplicates will be ignored in this case, because sets does not accept duplicates. If you have duplicate values take care otherwise it will be omitted.

Example:


set_1 = {1, 2, 3, 6, 8, 11}
set_2 = {3, 4, 5, 7, 13, 15}

print("Set one:", set_1)
print("Set two: ", set_2)

joined_set = set_1 | set_2
print("After sets joined: ", joined_set)

Output:


Set one: {1, 2, 3, 6, 8, 11}
Set two:  {3, 4, 5, 7, 13, 15}
After sets joined:  {1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 15}

Another Ways to Perform Union Operation Between Sets in Python is by Using the update() Method

As you know, The update() method adds elements from one set to another, this will effectively joining or combines the two sets.

Example:


set_1 = {1, 2, 3, 6, 8, 11}
set_2 = {3, 4, 5, 7, 13, 15, 18, 20}

print("Set one:", set_1)
print("Set two: ", set_2)

set_1.update(set_2)
print("After sets joined: ", set_1)

Output:


Set one: {1, 2, 3, 6, 8, 11}
Set two:  {3, 4, 5, 7, 13, 15, 18, 20}
After sets joined:  {1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 15, 18, 20}

Another Ways to Perform Union Operation Between Sets in Python is by Using the Set Comprehension

The third way that will allow you to combine or join sets by using the set comprehension. This will allow you to combine elements from multiple sets into a new set.

Example:


set_1 = {1, 2, 3, 6, 8, 11}
set_2 = {3, 4, 5, 7, 13, 15, 18, 20}

print("Set one:", set_1)
print("Set two: ", set_2)

joined_set = {x for x in set_1} | {x for x in set_2}
print("After sets joined: ",joined_set)

Output:


Set one: {1, 2, 3, 6, 8, 11}
Set two:  {3, 4, 5, 7, 13, 15, 18, 20}
After sets joined:  {1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 15, 18, 20}

Set Method to Sort Sets Items using sorted()

As you know already, Sets in Python are inherently unordered, this means they do not have a specific order for their elements. However, you cannot directly sort a set elements.

If you want to work with sorted elements, the best option is to convert the set to a list, then sort the list, and finally create a new set from the sorted list. See the example I have given to you.

Example:


my_set = {5, 1, 3, 2, 4, 7, 10, 89}
sorted_list = sorted(my_set)
sorted_set = set(sorted_list)

print("Original Set:", my_set)
print("Sorted Set:", sorted_set) 

Output:


Original Set: {1, 2, 3, 4, 5, 7, 10, 89}
Sorted Set: {1, 2, 3, 4, 5, 7, 10, 89}

Set Method to Copy Sets Items using copy()

Is very easy to copy set items in Python. You can create a shallow copy of a set using the copy() method or by using the set() constructor.

Both methods create a new set with the same elements as the original set. Let me show this by example:

Example:


original_set = {5, 1, 3, 2, 4, 7, 10, 89}
copied_set = original_set.copy()

print("Original Set:", original_set)
print("Copied Set:", copied_set)

print("\nAfter using set constructor Method\n")

original_set = {5, 1, 3, 2, 4, 7, 10, 89}
copied_set = set(original_set)

print("Original Set:", original_set)
print("Copied Set:", copied_set) 

Output:


Original Set: {1, 2, 3, 4, 5, 7, 10, 89}
Copied Set: {1, 2, 3, 4, 5, 7, 10, 89}

After using set constructor Method

Original Set: {1, 2, 3, 4, 5, 7, 10, 89}
Copied Set: {1, 2, 3, 4, 5, 7, 10, 89}

Convert Sets to Integer or Float

If you need to convert a set value to an integer or a float, you might need to perform some operation to summarize or extract a single value from the set.

Let me show an example of how we can able to convert a set of numbers to an integer and float.

Example:


my_set = {3, 4, 5, 7, 13, 15, 18, 20}

# Convert the set to an integer (e.g., try to find the sum of set)
int_value = sum(my_set)

# Convert the set to a float (e.g., try to find the average)
float_value = sum(my_set) / len(my_set)

print("Set value converted to Integer:", int_value)
print("Set value converted to Float:", float_value)

Output:


Set value converted to Integer: 85
Set value converted to Float: 10.625

Convert Sets to Tuple in Python

In Python is easy to convert a Set elements into Tuple. This process can allow you to easily convert a Set to a Tuple by using the tuple() constructor. Consider the following example.

Example:


my_set = {3, 4, 5, 7, 13, 15, 18, 20}
set_to_tuple = tuple(my_set)
print("After sets converted to a tuple:", set_to_tuple)

Output:


After sets converted to a tuple: (3, 4, 5, 7, 13, 15, 18, 20)

Convert Sets to List in Python

Is not difficult to convert a Set values to a list. In Python is easy to convert a set to a list using the list() constructor. Let me give you an example of how to perform such task.

Example:


my_set = {3, 4, 5, 7, 13, 15, 18, 20}
list_from_set = list(my_set)
print("After sets converted to a list:", list_from_set)

Output:


After sets converted to a list: [3, 4, 5, 7, 13, 15, 18, 20]

Convert Sets to Dictionary in Python

let me explain another ways of converting set items to a dictionary. It is not magic to convert a set to a dictionary, you only need to provide a key for each element in the set. You can do this using a dictionary comprehension.

Example:


my_set = {"apple", "banana", "cherry"}
dictionary_from_set = {fruit: len(fruit) for fruit in my_set}
print("Dictionary from Set:", dictionary_from_set)

Output:


Dictionary from Set: {'apple': 5, 'cherry': 6, 'banana': 6}

Perform Operation that Compare Sets in Python

If you want to compare sets in Python in order to determine relationships between them, such as equality or subset/superset relationships.

Example:


set_1 = {1, 2, 3}
set_2 = {3, 2, 1}
set_3 = {1, 2, 3, 4, 5}

# Check if two sets are equal
are_equal = set_1 == set_2

# Check if set_1 is a subset of set_3
is_subset = set_1.issubset(set_3)

# Check if set_3 is a superset of set_1
is_superset = set_3.issuperset(set_1)

print("Are Equal:", are_equal)
print("Is Subset:", is_subset)
print("Is Superset:", is_superset)

Output:


Are Equal: True
Is Subset: True
Is Superset: True

Perform Mathematical Operations in Sets

Performing a Mathematical operations like summation, division, or multiplication are applicable to sets. We can easily use functions, or methods such as sum() or multiplication and division symbols such as * or /. Let me show these with examples.

Example:


# Perform Mathematical Operations in Sets
my_set_1 = {3, 4, 5, 7}
my_set_2 = {10, 20, 30}


# Summ all items in a sets using sum() method
print("Sum of all set 1 values: ", sum(my_set_1))
print("Sum of all set 2 values :",sum(my_set_2))

Summation = sum(my_set_1) + sum(my_set_2)
print("Sum of all values in set 1 and set 2 : ", Summation)

# Perform divition
divition = sum(my_set_2) / sum(my_set_1)
print("Set value converted to Float:", divition)

# Multiplication 
multipilication = divition * sum(my_set_1)
print("Multiplication performed :", multipilication)

Output:


Sum of all set 1 values:  19
Sum of all set 2 values : 60
Sum of all values in set 1 and set 2 :  79
Set value converted to Float: 3.1578947368421053
Multiplication performed : 60.0

Example:


# Create integer variable
a = 60
b = 5

# Perform / operation
result = a / b

print(int(result/2))

Output:


12.0
12
6
<class 'str'>

Conlusion

In this blog, we've explored a fascinating aspect of Python sets. Think of sets as special containers with some unique tricks up their sleeves. They're like a bag where every item is one-of-a-kind, and there's no specific order to how they're stored.

Creating Python sets is easy; you can use curly braces {} or the set() function. However, getting items from sets requires a bit of a twist, as you can't grab items by their position like you would in a list. Changing sets is also interesting; you can add or remove items but can't directly tweak individual ones.

Python Sets are pretty good at math, allowing you to do operations like combining sets, finding common elements, and spotting differences. Surprisingly, they can even handle numbers in a math-like way.

You can compare Python sets for equality or see if one set is like a smaller version of another. Sets can also transform into other shapes, like tuples, dictionaries, or lists. One of their cool features is that they naturally remove duplicate items, which can be super handy.

So, understanding sets in Python is like adding a unique tool to your programming toolbox, no matter if you are expert or beginner. They shine when you need to work with collections of distinct items efficiently and elegantly. Check the benefits of learning Python.

Check References for Further

w3schools

Python Docs

Python Tutorial

Categorized in: