codescracker
python

Python Sets



« Python Tutorial Python Examples »

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

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:

python sets use curly braces

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:

python sets

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:

python sets duplicate item example

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:

python sets get unique elements from list using set

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:

python set example 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:

python set the set constructor

Important - Remember the double (()) or brackets

Set Operations

With the help of sets in Python, we can perform:

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:

python sets set operation example

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:

python sets example

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:

python sets with items of multiple data types

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:

python sets add multiple elements to set

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:

python add sets

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:

python sets print length of set

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:

python sets check element availability in set

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:

python sets remove elements from set

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:

python sets pop clear method to remove items from set

Python Online Test


« Python Tutorial Python Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker