0% found this document useful (0 votes)
3 views24 pages

Module 3

Module 3 covers compound data types in Python, specifically focusing on lists, tuples, and dictionaries. It details list operations such as indexing, slicing, concatenation, and various methods for manipulating lists, including appending, inserting, and removing elements. Additionally, it discusses mutability, aliasing, cloning, and how lists can be used as parameters in functions.

Uploaded by

Monisha GP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

Module 3

Module 3 covers compound data types in Python, specifically focusing on lists, tuples, and dictionaries. It details list operations such as indexing, slicing, concatenation, and various methods for manipulating lists, including appending, inserting, and removing elements. Additionally, it discusses mutability, aliasing, cloning, and how lists can be used as parameters in functions.

Uploaded by

Monisha GP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Module 3

COMPOUND DATA: LISTS, TUPLES, DICTIONARIES


Lists

List is an ordered sequence of items. Values in the list are called elements / items.

It can be written as a list of comma-separated items (values) between square
brackets[ ].

Items in the lists can be of different data types.


Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

operations examples description


Building >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
lists/create a list >>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

List slices:

List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]

default start value is 0

default stop value is n-1

[:] this will print the entire list

[2:2] this will create a empty slice
slices example description
a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step
>>> a[0:6:2] size 2.(from index[0] to 2nd
[9, 7, 5] element and from that
>>> a[0:6:3] position to next 2nd element
[9,6]

List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)

syntax example description


1 >>> a=[1,2,3,4,5]
>>> a.append(6) Add an element to
a.append(element) >>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]
2 a.insert(index,element) >>> a.insert(0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>> a.extend(b) Add all elements of a
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returns the index of
a.index(element) >>> a.index(8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sort items in a list in
sum()
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>> a.reverse()
Reverse the order of
a.reverse() >>> print(a)
items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>> a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>> a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>> a.count(6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined

List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:
The for loop in Python is used to iterate over a sequence (list, tuple, string) or otheriterable
objects.
Iterating over a sequence is called traversal.

Loop continues until we reach the last item in the sequence.

The body of for loop is separated from the rest of the code using indentation.

Syntax
for val in sequence:

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop

The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

When the condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

Mutability:

Lists are mutable. (can be changed)

Mutability is the ability for certain types of data to be changed without entirely
recreating it.

An item can be changed in a list by accessing it directly as part of the assignment
statement.

Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.
Example description

>>> a=[1,2,3,4,5] changing single element


>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

Aliasing(copying):

Creating a copy of a list is called aliasing.


When you create a copy both the list will be having same memory location.


changes in one list will affect another list.

Alaising refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]


In this a single list object is created and modified using the subscript operator.

When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.

This type of change is what is known as a side effect. This happens because after
the assignment b=a, the variables a and b refer to the exact same list object.

They are aliases for the same object. This phenomenon is known as aliasing.

To prevent aliasing, a new object can be created and the contents of the original
can be copied which is called cloning.

Clonning:

To avoid the disadvantages of copying we are using cloning.

Creating a copy of a same list of elements with two different memory locations is called cloning.


Changes in one list will not affect locations of aother list.

Cloning is a process of making a copy of the list without modifying the original list.

1. Slicing
2. list()method
3. copy() method

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method

a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
Lists and Functions/ List as parameters:

In python, arguments are passed by reference.

If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.

When a list to a function is passed, the function gets a reference to the list.

Passing a list as an argument actually passes a reference to the list, not a copy of the list.

Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)

Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)

Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)

Multidimensional lists:

Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes.
The first index dictates which list value to use, and the second indicates the value within the list
value. Ex, spam[0][1] prints 'bat', the second value in the first list.

Negative Indexes

 We can also use negative integers for the index. The integer value -1 refers to the last index in a list,the
value -2 refers to the second-to-last index in a list, and so on.

Using for Loops with Lists

 A for loop repeats the code block once for each value in a list or list-like value.
Program

Output:

 A common Python technique is to use range (len(someList)) with a for loop to iterate over the
indexes of a list.

 The code in the loop will access the index (as the variable i), the value at that index (as supplies[i]) and
range(len(supplies)) will iterate through all the indexes of supplies, no matter how many items it contains.

Nested lists:
there is a list containing a list inside itself as an element(sublist) or data, then that list is known
as a nested list.

Example:
# creating a nested list
Nested_List = [10, 20, 30,['a', 'b', 'c'], 50]

# accessing the sublist by using the indexing method


Sub_List = Nested_List[3]

# accessing the second element of the sublist


data = Nested_List[3][1]

print("List inside the nested list: ", Sub_List)


print("Second element of the sublist: ", data)

OUTPUT:
List inside the nested list: ['a', 'b', 'c']
Second element of the sublist: b

Comparison between Lists and Generators

Here are some other key differences between a generator and a list:
 Lists are mutable, meaning you can modify them after creation, whereas
generators are immutable and their values cannot be modified once they are
generated.
 Lists can be indexed and sliced, whereas generators cannot be directly indexed
or sliced. Instead, you can iterate over them using a for loop or convert them to
a list using the list() function.
 Lists can be iterated over multiple times, whereas generators can only be
iterated over once. Once a generator has been exhausted, you cannot iterate
over it again.

A sparse matrix is a matrix in which most of the elements are zero. Typically, a matrix is

considered sparse if more than half of its elements are zero.

Examples:

0 0 0 1 0
2 0 0 0 3
0 0 0 4 0

Above is sparse matrix with only 4 non-zero elements.


Here's a Python program to check if a given matrix is sparse or not:

Tuple:

A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.

A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to
a tuple or remove elements from the tuple.

But tuple can be converted into list and list can be converted in to tuple.

methods example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:

Tuples are faster than lists.

If the user wants to protect the data from accidental changes, tuple can be used.

Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:

Tuple is immutable so changes cannot be done on the elements of a tuple once it is
assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.

Tuple Assignment:

Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.

Multiple assignment works by creating a tuple of expressions from the right hand
side, and a tuple of targets from the left, and then matching each expression to a
target.

Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:

It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

Tuple as return value:



A Tuple is a comma separated sequence of items.

It is created with or without ( ).

A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tuple as argument:

The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')

Mutability and tuples,


Immutable (tuple)

Immutable Objects are of in-built datatypes like int, float, bool, string, Unicode, and tuple. In simple words, an
immutable object can’t be changed after it is created.

Example:
# Python code to test that
# tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
output:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
Mutable Objects
Mutable Objects are of type Python list, Python dict, or Python set. Custom classes are generally

mutable. Lists are mutable in Python. We can add or remove elements from the list

Example:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)

my_list.insert(1, 5)
print(my_list)

my_list.remove(2)
print(my_list)

popped_element = my_list.pop(0)
print(my_list)
print(popped_elemen

Output:

[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4]
[5, 3, 4]
1

Difference between List, Tuples

List Tuples
A list is mutable A tuple is immutable
Lists are dynamic Tuples are fixed size in nature

List are enclosed in Tuples are enclosed in parenthesis ( )


brackets[ ] and their and cannot be updated
elements and size
can be changed
Homogenous Heterogeneous
Example: Example:
List = [10, 12, 15] Words = ("spam", "egss")
Or
Words = "spam", "eggs"
Access: Access:
print(list[0]) print(words[0])
Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57

Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)

Matrix multiplication Output


a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)

Matrix transpose Output


a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
SETS

What is sets in python


A set is an unordered collection with no duplicate elements, no indexing, and must be
immutable (cannot be changed).
How we can use sets in Python
You can declare a variable and then is equal to, and you define the items (elements)
inset in the curly bracket {} , separated by comma, or by using the built-in set() function.
You can define multiple values and they may be of different types (integer, float, tuple,
string etc.). However, a set cannot contain elements that are mutable, such as lists,
sets, or dictionaries. For example
1A = {1, 2, 5, 4, 7, 9}
Note: but keep in mind that the set cannot have duplicate values.
For example, what happens when we define a set with some duplicate values. I’m going
to declare the set, and you can see the 2, which was a duplicate. Which we have
defined here is removed from this set.
1
2A = {1, 2, 5, 4, 7, 9, 2}
3print(A)
4Output: {1, 2, 4, 5, 7, 9}
A set always has unique values, and if you define a set with duplicate values, it’s going
to remove the duplicate values and only save the unique values in the set.
You can find the length of a set using this len() method and the set’s name, which
returns a set’s size.
1
2A = {1, 2, 5, 4, 7, 9, 2}
3print(len(A))
4Output: 6

Set operation
Sets are mutable. But indexing has no meaning because it is unordered.
No element of a set can be accessed or changed by indexing or slicing. Set data
type does not support it.
One element may be added with the add() method and several items with
the update() method. Update() can make the argument with tuples, lists, strings, or other
sets. Duplicates will be avoided in all cases.
To add an element in a set. I want to add 10, for example, into my set.
#!/usr/bin/python
1A = {1, 2, 5, 4, 7, 9, 2}
2A.add(10)
3print(A)
4Output: {1, 2, 4, 5, 7, 9, 10}
5
You can see 10 is added to the set, but this time will only be added if it’s already not
there in the set. If it’s already there in the set, nothing will happen.
Let’s try to add 10 to this set, which already has a set, and once again, you will see that
nothing happens inside the set because 10 was already there.
1
2A = {1, 2, 5, 4, 7, 9, 2, 10}
3A.add(10)
4print(A)
5Output: {1, 2, 4, 5, 7, 9, 10}
If you want to add multiple values in a set, you can use update() methods. You can call
this method, which is an update, and then inside the curly brackets {} , you need to
provide these multiple values. Let’s add some values to this set.
1
2A = {1, 2, 5, 4, 7, 9, 2, 10}
3A.update([15, 18, 17, 14])
4print(A)
5Output: {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
You can see all these values are added to the set.
Removing elements from a set in python

You can remove one item from a set using the methods discards() and remove() .
You can also remove the values from the set. We can use a method called remove() . We
want to remove 18 from the set.
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
3A.remove(18)
4print(A)
5Output: {1, 2, 4, 5, 7, 9, 10, 14, 15, 17}
discard() method
This method works similarly to the remove() method. For example, I want to remove this
17 from my set. I can write 17.
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17}
3A.discard(17)
4print(A)
5Output: {1, 2, 4, 5, 7, 9, 10, 14, 15}
Difference between a discard() method and a remove() method
Whenever you use a remove() method, you try to remove an element that is not there in
the set.
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
3A.remove(100)
4print(A)
5Output: KeyError: 100
I will try to remove 100, which is not there in the set. It’s going to throw an exception,
and it says KeyError: 100 .
Suppose you try to do the same thing using a discard() method. Try to discard() a hundred
from the set, which is not there in the set.
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
3A.discard(100)
4print(A)
5Output: {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
It’s not going to give me any error, and that’s the difference between
this discard() and remove() , so remove() throws an error. When an element is not there, but
this discard() doesn’t throw any error, it’s not going to do anything if the value is not there
in the set.

pop() method
It’s going to remove any random element from your set. It doesn’t need to remove the
element from the left-hand side or the right-hand side. It will remove any random
element from the set. for example
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
3A.pop()
4print(A)
5Output: {2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
clear() method
Suppose you want to clear the set. You can use a clear() method. I can use
the clear() method to empty the set.
1
2A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
3A.clear()
4print(A)
5Output: set()
When I try to access the set’s values, you can see it’s an empty set with no values.
del() method
If you want to delete a set, you can use a del() function and your set’s name.
A = {1, 2, 4, 5, 7, 9, 10, 14, 15, 17, 18}
1del A
2print(A)
3Output: NameError: name 'A' is not defined
4
5
You delete it when you try to access it. It’s going to give you an error that NameError:
name 'A' is not defined .

How to create a set using a set constructor


You can also create a set using a set constructor. Instead of these curly brackets {} ,
you can write set and in the double parentheses. You need to provide the double
parentheses.
1
2name = set(('max', 'tom', 'den'))
3print(name)
4Output: {'tom', 'max', 'den'}
Here to create a set using the set constructor. It will also create the set called name
and when I try to access the values inside the set name. You can see it has created
this set of names. Also, you can convert a list into a set. Let me define the Z variable,
and then I can use a set constructor, and inside these parentheses, I can use the square
brackets. Which we generally use with lists, and then you can define your list here.
1
2Z = set([1, 2, 3, 4])
3print(Z)
this list will be converted to a set, and you can see the result here
Output: {1, 2, 3, 4}

1
Mathematical sets Operation / Set Quantification with all and any
Now similar to the mathematical set operations like Union, intersection, symmetric
difference, etc. You can also use these mathematical operations related to the set on
the Python.
Let’s see how we can use these mathematical set operations on Python sets. Let me
once again define a set. I have already one set A. which contains these values, for
example
1A = {2, 4, 5, 7, 9, 10, 14, 15}
and I will define a set B with some other set of values. I am going to define a set with,
for example.
1B = {10, 11, 12, 13, 14, 16, 18}
Union Method
Now I have two sets, and on these two sets, I want to perform some set operations,
which are also used in mathematics. You can find out the union of two sets using an
operator called or. when I write
1A = {2, 4, 5, 7, 9, 10, 14, 15}
2B = {10, 11, 12, 13, 14, 16, 18}
3print(A | B)
4Output: {2, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15, 16, 18}
5
It’s going to give me the Union of these two sets. Union of two sets contains all the
elements in set A or inset B. you can see it’s going to give me the Union of A and B.
that means this set contains all the elements in set A or set B. I can use a method called
Union instead of this or operator.
I can use another way to use union methods with dot operator.
1
2A = {2, 4, 5, 7, 9, 10, 14, 15}
3B = {10, 11, 12, 13, 14, 16, 18}
4print(A.union(B))
5Output: {2, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15, 16, 18}
Which is going to give you the same answer. You can either use print(A.union(B)) method
or using print(A | B) operator.
intersection Method
Now let’s see how we can find out the intersection between two sets. To find out the
intersection, you use the ‘&’ operator.
1
2A = {2, 4, 5, 7, 9, 10, 14, 15}
3B = {10, 11, 12, 13, 14, 16, 18}
4print(A & B)
5Output: {10, 14}
the intersection of two sets contains all the elements that are there in both the set that
means set A and set B. you can see it gives me two elements inside the set and these
two elements are there both in the A set and the B set. That’s why we get only two
values because these two values are there in set A and set B.
you can use a method called the intersection
1
2A = {2, 4, 5, 7, 9, 10, 14, 15}
3B = {10, 11, 12, 13, 14, 16, 18}
4print(A.intersection(B))
5Output: {10, 14}
which is going to give me the same answer. either you can
use print(A.intersection(B)) method or you can use print(A & B) .

what is a difference between two set


A difference of two sets contains all the elements in A but not in B. you can find out the
difference by the minus '-' operator.
1A = {2, 4, 5, 7, 9, 10, 14, 15}
2B = {10, 11, 12, 13, 14, 16, 18}
3print(A - B)
4Output: {2, 4, 5, 7, 9, 15}
5
When you write A minus B, you will be able to differentiate between these two sets.
This result will contain all the elements that are in A but not in B. you can also use B
minus A, and then is going to give you other results, because this time it’s going to
provide you with a set which contains all the elements that are there in B and not in A.
difference between set A minus B is different from B minus A.
Also, you can use a different method.
1
2A = {2, 4, 5, 7, 9, 10, 14, 15}
3B = {10, 11, 12, 13, 14, 16, 18}
4print(A.difference(B))
5Output: {2, 4, 5, 7, 9, 15}
it’s going to give you the same kind of answer.
Symmetric Difference between two Sets
Symmetric difference between two sets contains all the elements in set A but not in set
B, or they are inset B but not in set A. you can find out the symmetric difference using
the '^' symbol and then B.
1
2A = {2, 4, 5, 7, 9, 10, 14, 15}
3B = {10, 11, 12, 13, 14, 16, 18}
4print(A ^ B)
5Output: {2, 4, 5, 7, 9, 11, 12, 13, 15, 16, 18}

all function
We can see that all the entries in this list are True, but the best way to determine this in code
is to use Python’s all function:
>>> S = {1, 2, 3, 4, 5, 6, 7, 8}
>>> S
{1, 2, 3, 4, 5, 6, 7, 8}
>>> all([x > 0 for x in S])
True
The all function returns True if all the elements in a list, set, or other iterable possesses a
particular quality.
We do not need to create a list; a generator expression is better (note that parentheses
replace the square
brackets):
>>> all((x > 0 for x in S))
True
and in this case the inner parentheses are superfluous. We can write the expression as
>>> all(x > 0 for x in S)
True
Are all the elements of S greater than 5?
>>> all(x > 5 for x in S)
False

You might also like