Module 3
Module 3
>>> 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]
List methods:
Python provides methods that operate on lists.
syntax:
list name.method name( element/index/list)
>>>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.
The body of for loop is separated from the rest of the code using indentation.
Syntax
for val in sequence:
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
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
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.
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]
OUTPUT:
List inside the nested list: ['a', 'b', 'c']
Second element of the sublist: b
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
Examples:
0 0 0 1 0
2 0 0 0 3
0 0 0 4 0
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 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')
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
List Tuples
A list is mutable A tuple is immutable
Lists are dynamic Tuples are fixed size in nature
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)
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 .
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) .
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