Welcome to this tutorial on How to Create a Python Set, which is used to store multiple Elements into a single Python Variable.
Python Sets are Unordered, Mutable and do not allow for Duplicates. The easiest way to recognize a Python Set, is by its usage of Braces { }.
Sets are one of 4 built-in data types in Python, that are used to store collections of data. The other 3 Python Iterables (Collection Data Types) are Lists, Tuples, and Dictionaries, each with their own different qualities and usages.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python, as well as Python Variables and Data Types.
With that said, let’s get started with this free Python Set tutorial.
How to Create a Set in Python
A Python Set is created using Braces { }, in which its Elements are stored. A Set is assigned to a Variable name as follows:
Set_Variable_Name = {Set_Element0, Set_Element1, Set_Element2, Set_Element3}
Python Set Example:
Here is a Python Set that contains three fruits as its Elements, in the form of Strings, assigned as a Variable named “fruit_set”:
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
#>> {'apple', 'orange', 'banana'}
We then print out the “fruit_set” Variable by using the “print(fruit_set)” statement. Python outputs {‘apple’, ‘orange’, ‘banana’} which is our Set of fruits.
Braces { } are Required when creating a Python Set
A Set cannot be created without the use of Braces { }.
fruit_set= "apple", "orange", "banana"
print(fruit_set)
#>> ('apple', 'orange', 'banana') # A Tuple Is created instead of the intended Set
As we can see, the Braces { } are a requirement when creating a Python Set, as it defaults to a Tuple when not used.
Python Sets work with only a Single Element
A Python Set can be created with only one Element, which unlike a Tuple, requires 2 more more Elements.
For example, if there is only one Element in the Set, such as “apple”, it remains a Set. We can test this using the type() Function:
fruit_set = {"apple"}
print(fruit_set)
print(type(fruit_set)) # Calling the “fruit_set” Variable inside of the type() Function
#>> {'apple'}
#>> <class 'set'> # Confirmation that this is in fact a Set
The “apple” is the only value in the Set, yet Python still accepts it as a legitimate Set, which we can see when using the type() Function. This is the opposite of a Tuple, which would output “apple” as a String.
Python Sets don’t require any Elements
Python Sets can even be completely empty, requiring no values at all, although it will be output as a Dictionary (dict) and not a Set by Python:
fruit_set = {}
print(fruit_set)
print(type(fruit_set)) # Calling the “fruit_set” Variable inside of the type() Function
#>> {}
#>> <class 'dict'> # Becomes a Dictionary and not a Set
While it may seem as though an empty Set was output, it is in fact a Dictionary and not a Set. In order to create an empty Set, we have to use the set() Function.
Data Types that a Python Set can contain
Python Sets can contain any of the following Data Types as Elements, both individually or mixed within a single Set:
- Integers (int) – Whole numbers such as: 1, 14, 576.
- Floating Point (float) – Decimal values such as: 1.24, 5.6 and Fractional Values such as 1/2, 9/6.
- Strings (str) – Sequence of Characters such as: “I love Python”, “this course is great”, “year 3000”.
- Booleans (bool) – Logical values representing: TRUE or FALSE.
For example, we are able to create the following mixed Data Type Set:
mixed_set = {14, 365.34, "welcome", True} #int, float, string, bool
print(mixed_set)
#>> {'welcome', 365.34, 14, True}
All four Data Types, including the int, float, string and bool were successfully output within the Set.
Python Iterables that can be stored within a Set
Python Sets aren’t limited to only storing single Data Types either, as they are able to store Python Iterables (Collection Data Types) as well.
Sets are however limited to only being able to store Tuples as Elements. This is unlike Lists and Tuples, which can store all 4 Iterables including Lists, Tuples, Sets, Dictionaries as Elements.
Here is an example of a Python Set with a Tuple stored as its Element:
mixed_iterable_set = {("apple", "orange")} # tuple
print(mixed_iterable_set)
#>> {('apple', 'orange')}
Using the Print Statement to output the results, we can see that Python successfully accepted the Tuple Iterables as an Element within the Set.
How to Check for a Python Set using the type() Function
If you are unsure if a variable or output is in fact a Set, you can easily check this using the type() Function:
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
print(type(fruit_set)) # type() Function within Print Statement
#>> {'apple', 'orange', 'banana'}
#>> <class 'set'> # Confirmation that this is a Set
Python outputs <class ‘set’>, which confirm to us that the Variable is indeed a Set.
How to Check the Length of a Python Set using len() Function
The length of a Python Set can be defined using the len() Function:
fruit_set = {"apple", "orange", "banana"}
print(len(fruit_set))
#>> 3
This outputs the number 3 (int), which tells us how many Elements we have in our Python Set.
Python Sets are Unordered, Mutable & Don’t Allow Duplicates
A Python Sets is Unordered, Mutable, and DO NOT allow for Duplicate Elements.
Python Sets are Unordered
Python Sets are Unordered and thus the Elements within a Set have no defined order.
Being Unordered means that every time a Python Set is output by Python (such as using a Print Statement), the order of the items in the Set will change.
# FIRST RUN
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
#>> {'orange', 'banana', 'apple'} #Different output order
# SECOND RUN
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
#>> {'banana', 'orange', 'apple'} #Different output order
# THIRD RUN
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
#>> {'apple', 'banana', 'orange'} #Different output order
Each output run will change the order of the value of the original Set, unlike Lists, Tuples, and Dictionaries, which remain in the same order every time.
Python Sets are Mutable
Python Sets are also Mutable, meaning that we can be change, add and remove Elements in a Set, after it has been created, using the available List Methods:
Python Set Methods
- add() : Adds an Element to a Set
- clear() : Removes all Elements of a Set
- copy() : Returns a Copy of a Set
- difference() : Returns a Set that contains the difference between two or more Sets
- difference_update() : Removes the Elements in a Set that are also included in another, specified set
- discard() : Removes a specified Element from a Set
- intersection() : Returns a Set, that is an intersection of another two Sets
- intersection_update() : Removes the Elements in a Set that are not present in other, specified set(s)
- isdisjoint() : Returns whether two Sets have a intersection or not
- issubset() : Returns whether another Set contains this Set or not
- issuperset() : Returns whether this set contains another set or not
- pop() : Removes the Element at the end of a Set
- remove() : Removes an Element with a specified Value
- symmetric_difference() : Returns a set with the symmetric differences between two sets
- symmetric_difference_update() : Inserts the symmetric differences from this set and another
- union() : Returns a Set that contains the union of sets
- update() : Updates the Set with the union of this set and other Sets
Python Sets Do Not Allow Duplicates
Python Sets Do Not allow for duplicate Elements:
fruit_set = {"apple", "orange", "banana", "apple"}
print(fruit_set)
#>> ('apple', 'orange', 'banana')
Here we can see that we cannot have two copies of the “apple” Element.
Python Set Conclusion
I hope you enjoyed this tutorial on how to create a Python Set. This should give you the starting knowledge you need to easily create Sets in Python for your code or project.
Python Set Summary
Here is a summary of what we learnt when creating a Python Set:
- Python Sets use and require Braces { }.
- Python Sets can be created using a single Element.
- Python Sets can be empty with no Elements at all, but does output as a Dictionary.
- Python Sets can contain Integer (int), Floating Point (float), Strings (str) and Booleans (bool) Data Types as their Elements.
- Python Sets can only contain one other Python Iterables, which is a Tuples as an Element.
- The type() Function can be used to check if a Variable is a Set.
- The len() Function can be used to check the Length of a Set.
- Python Sets are Unordered, meaning that the Elements will not have a defined order, as it will change at each runtime.
- Python Sets are Mutable, meaning that Elements can be changed, added, removed, sorted, reversed using Methods.
- Python Sets do not allow for Duplicate Elements, meaning that it is not possible to have two or more of the same Elements in a Set.
Remember, that when choosing a the Python Iterables (List, Tuple, Set or Dictionary) for your code, it is very important to choose the correct one for the required use case, as each of the Python Iterables has it own qualities and properties, which have a direct influence on both performance and security of your code.
Full Python Beginners Course
This tutorial is just a small sample of the my Full Python Beginners Course. The entire course is recorded and available in High Definition video, allowing you to easily learn Python as you watch and follow along. If you have been wanting to start learning Python, but haven’t been sure where to start, then this is the course for you, so don’t to miss out!
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!