Skip to content
Amin Zamani edited this page Mar 23, 2023 · 1 revision

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed and do not allow duplicate values. Sets are written with curly brackets.

Create a Set:

this_set1 = set()
this_set2 = {"apple", "banana", "cherry"}

Set Constructor

It is also possible to use the set() constructor to make a set.

Using the set() constructor to make a set:

this_set = set(("apple", "banana", "cherry"))  # note the double round-brackets
print(this_set)

Set Properties

Note: Set items are unchangeable, but you can remove items and add new items.

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

'Unordered' means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Duplicate values will be ignored:

this_set = {"apple", "banana", "cherry", "apple"}
print(this_set)

Set Items Data Types

Set items can be of any data type.

String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}

Why use sets?

sets are an easy eay to remove duplicates from a collection.

Get the Length of a Set

To determine how many items a set has, use the len() function.

Get the number of items in a set:

this_set = {"apple", "banana", "cherry"}
print(len(this_set))

Type

From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>

What is the data type of a set?

this_set = {"apple", "banana", "cherry"}
print(type(this_set))

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Loop through the set, and print the values:

this_set3 = {"apple", "banana", "cherry"}
for x in this_set3:
    print(x)

Check if "banana" is present in the set:

this_set4 = {"apple", "banana", "cherry"}
print("banana" in this_set4)

Change Items

Once a set is created, you cannot change its items, but you can add new items.

Add Items

To add one item to a set use the add() method:

this_set5 = {"apple", "banana", "cherry"}
this_set5.add("orange")
print(this_set5)

Add Sets

To add items from another set into the current set, use the update() method.

Add elements from tropical into this_set:

this_set5 = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
this_set5.update(tropical)
print(this_set5)

Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

Add elements of a list to at set:

this_set6 = {"apple", "banana", "cherry"}
my_list = ["kiwi", "orange"]
this_set6.update(my_list)
print(this_set6)

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

Note: If the item to remove does not exist, remove() will raise an error.

Remove "banana" by using the remove() method:

this_set = {"apple", "banana", "cherry"}
this_set.remove("banana")
print(this_set)

Note: If the item to remove does not exist, discard() will NOT raise an error.

Remove "banana" by using the discard() method:

this_set = {"apple", "banana", "cherry"}
this_set.discard("banana")
print(this_set)

You can also use the pop() method to remove an item, but this method will remove the last item.

Remember that sets are unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

this_set = {"apple", "banana", "cherry"}
x = this_set.pop()
print(x)
print(this_set)

The clear() method empties the set:

this_set9 = {"apple", "banana", "cherry"}
this_set9.clear()
print(this_set9)

The del keyword will delete the set completely:

this_set = {"apple", "banana", "cherry"}
del this_set
print(this_set)

Loop Items

You can loop through the set items by using a for loop.

Loop through the set, and print the values:

this_set11 = {"apple", "banana", "cherry"}
for x in this_set11:
    print(x)

Join Sets

There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another.

The union() method returns a new set with all items from both sets:

set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

# or

print(set1 | set2)

The update() method inserts the items in set2 into set1:

set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

Note: Both union() and update() will exclude any duplicate items.

Keep ONLY the Duplicates

The intersection_update() method will keep only the items that are present in both sets.

Keep the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

The intersection() method will return a new set, that only contains the items that are present in both sets.

Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

# or

print(x & y)

Keep All, But NOT the Duplicates

The symmetric_difference_update() method will keep only the elements that are NOT present in both sets.

Keep the items that are not present in both sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.

Return a set that contains all items from both sets, except items that are present in both:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

difference - : returns new set with members from left not in right.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
print(x - y)

Set Methods

Python has a set of built-in methods that you can use on sets.

add(): Adds an element to the set.

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

copy(): Returns a copy of the set.

difference(): Returns a set containing the difference between two or more sets.

difference_update(): Removes the items in this set that are also included in another, specified set.

discard(): Remove the specified item.

intersection(): Returns a set, that is the intersection of two other sets.

intersection_update(): Removes the items in this 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 an element from the set.

remove(): Removes the specified element.

symmetric_difference(): Returns a set with the symmetric differences of two sets.

symmetric_difference_update(): inserts the symmetric differences from this set and another.

union(): Return a set containing the union of sets.

update(): Update the set with the union of this set and others.

is

print({1, 2, 3} is {1, 2, 3})  # output: False
print({1, 2, 3} == {1, 2, 3})  # output: True

Python

Python Essentials 1 (PCEP)

Introduction to Python and computer programming

Data types, variables, basic I/O operations, and basic operators

Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations

Clean Code

Algorithms

Django

Django Rest Framework

API

pip

SQLAlchemy

FastAPI

Pytest

TDD

Git

Linux

Docker

Python Testing

Interview Questions

Clone this wiki locally