- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python CGI Programming
- Python Network Programming
- Python Send E-mail
- Python Multi-threading
- Python XML Processing
- Python MySQL Database
- Python GUI Programming
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
Python Sets
This article provides you the easy way to learn all about Sets in Python with the help of not only theory, but with example programs and their respective outputs. This article deals with:
- Set definition and its syntax
- Precaution of using curly braces
- Get unique elements from list using set
- Add new items to a set
- The set() constructor
- Set Operations
- Set Example with item of multiple data types
- Add multiple items to a set
- Add two sets
- Find and print length of a set
- Check if an element is available in set or not
- Remove an element from a set
Set Definition
Like List, Tuple, and Dictionary, Set also stores one or more elements (of any data type) using single variable. In other words, we can say that, Set is a data type that can be used to store collections of data, or multiple items.
Set Syntax
Items of Set must be written in curly braces like shown in the sample code given below:
marks = {89, 87, 92, 67}
Precaution of Using Curly Braces
If you use curly braces to initialize an empty set, then it gets treated as dictionary. Therefore, use set() constructor to do the job. Here is an example:
my_set_one = {} print(type(my_set_one)) my_set_two = set() print(type(my_set_two))
Here is its sample output:
Note - The type() method returns the type of variable passed as its argument.
Set Items are Unordered
Unlike List, Tuple, and Dictionary, Set items are unordered. That is, if you print the set, then you'll get all the items of set, but in random order like shown in the sample output produced by the program given below:
marks = {89, 87, 92, 67, 78, 94}
print(marks)
Here is its sample output:
As you can see, the original order of the set is 89, 87, 92, 67, 78, 94, but the output's order is 67, 94, 87, 89, 92, 78.
Set Items can not be Indexed
Unlike Lists and Tuples, we can't access Set items using its indexes. Therefore, Sets in Python do not support any type of slicing operations.
Set Items are Unchangeable
Like Tuple, Set items are also unchangeable. That is, after initializing the set items, we can not change the item.
Set Items do not allows Duplicate Values
Like Dictionary, Set also don't allows any duplicate values. The program given below demonstrates it:
marks = {89, 87, 94, 87}
tmarks = marks
print(tmarks)
Here is its sample output:
As you can see, the mark 87 appears two times in the same set, therefore one 87 gets removed automatically.
Get Unique Elements from List using Set
Since set do not allows duplicates, therefore we can use set to extract all the unique elements from a list like done in the program given below:
places = ["NewYork", "California", "NewYork", "Los Angles", "California"] unique_places = set(places) print("\nUnique Places are:", unique_places)
Here is its sample output:
To remove all duplicates and return another list, use following code:
list(set(places))
In above code, the List named places gets converted into Set. So that, the Set removes duplicates, again the Set gets converted back into List. So the variable places is now a List of only unique elements.
Set allows to Add New Items
Set allows to add new items. The program given below illustrates how to add new items to already created set.
marks = {89, 87, 92, 67, 78, 94} print(marks) marks.add(99) print(marks)
The snapshot given below shows the output produced by above Python program:
The add() method helps to add new items to the set.
The set() Constructor
In place of curly braces, the set() constructor can also be used to define a set like shown in the program given below:
marks = set((89, 87, 94)) print("My Marks are:", marks)
The snapshot given below shows sample output produced by this Python program:
Important - Remember the double (()) or brackets
Set Operations
With the help of sets in Python, we can perform:
- Union using |
- Intersection using &
- Difference using -
- Symmetric Difference using ^
of any two sets just like we do in Mathematics. Therefore sets helps to achieve that goal. The program given below illustrates and shows all these four famous operations on sets:
set_one = {1, 2, 3, 4, 5} set_two = {2, 5, 7, 8, 9} print("\n------------Union of Two Sets------------------------") print(set_one, "|", set_two, "=", set_one | set_two) print("\n------------Intersection of Two Sets-----------------") print(set_one, "&", set_two, "=", set_one & set_two) print("\n------------Difference of Two Sets-------------------") print(set_one, "-", set_two, "=", set_one - set_two) print("\n------------Symmetric Difference of Two Sets---------") print(set_one, "^", set_two, "=", set_one ^ set_two)
This program produces the output that looks like:
Other two famous operations on sets are of checking issubset and issuperset. The table given below shows methods and its equivalent operators used to perform operations on set, supposing a and b are two sets:
Method | Operator | Method Example | Operator Example |
---|---|---|---|
intersection() | & | a.intersection(b) | a & b |
union() | | | a.union(b) | a|b |
difference() | - | a.difference(b) | a - b |
symmetric_difference() | ^ | a.symmetric_difference(b) | a ^ b |
issubset() | <= | a.issubset(b) | a <= b |
issuperset() | >= | a.issuperset(b) | a >= b |
Python Set Example
Here is an example of sets in Python:
mysets = {1, 2, (3, 4, 5), 6, (7, 8), (9, 10)}
print(mysets)
Here is its sample output:
Set Example with Items of Multiple Data Types
The example program given below on sets, shows a set with items of multiple data types, that are of string, boolean and int type:
student_detail = {"codescracker", True, 100} print(student_detail)
Here is its sample output:
Add Multiple Elements to a Set
Now the program given below shows how to add multiple elements to a set. The size of element and element itself are all must be entered by user at run-time like shown in the program and its sample run given below:
myset = {1, 2, 3} print("-------Original Set-------") print(myset) print("\nHow many elements to add in the set ?") tot = int(input()) print("Enter", tot, "elements:") for i in range(tot): val = input() myset.add(val) print("\n--------New Set-----------") print(myset)
Here is its sample output after providing exactly 4 as How many elements to add in the set ? and then 100, 200, 300, 400 as four elements to add:
Note - You're seeing the entered element is added as string data type, because while receiving the input using input() method, we've not used int() method to convert the input value to integer type. That is, anything received using input() gets treated as string type, by default.
Add Two Sets
Along with addition of new items to the set, we can also add the whole one set to another set. To do this job, the update() method helps to join two sets like shown in the program given below:
first_sem_marks = {89, 87, 94} print(first_sem_marks) second_sem_marks = {90, 93, 70} first_sem_marks.update(second_sem_marks) print(first_sem_marks)
Here is its sample output:
How to Find and Print Length of Set
The len() method is available in Python to achieve the goal of finding and printing the length of a set. Here is an example program that illustrates it:
student_detail = {"codescracker", "Programmer", True, 100} print("Set Items:", student_detail) print("Set Length:", len(student_detail))
This program produces the output as shown in the snapshot given below:
Check if an Element is Available in SET or not
The program given below shows, how to check whether an element is available in the Set or not:
myset = {1, 2, 3} print("Enter an Element to check: ") val = int(input()) if val in myset: print(val, "is available in the Set") else: print(val, "is not available in the Set")
Here is its sample run with user input, 3:
How to Remove an Element from a Set ?
Python provides two methods to do the job of removing an element from a set. The two methods are remove() and discard(). The program given below is an example that shows the use of both the methods in removing an element from the set:
myset = {1, 2, 3, 4, 5} print("------Original Set------") print(myset) myset.discard(5) print("-----Set after removing 5------") print(myset) myset.remove(2) print("-----Set after removing 2------") print(myset)
The snapshot given below shows sample output produced by this program:
To remove any random elements from the set, use pop() method. And to remove all the items from a set, use clear() method. The example program given below uses and illustrates these two methods:
myset = {1, 2, 3, 4, 5} print("------Original Set------") print(myset) myset.pop() print("-----Set after popping------") print(myset) myset.clear() print("-----Set after clearing-----") print(myset)
And the output produced by this Python program is:
« Previous Tutorial Next Tutorial »