Module - 4
Module - 4
List: Creating a List, List indexing and splitting, Python List Operations, List Built-in functions,
Tuple: Creating a tuple, Indexing, Deleting Tuple, Tuple operations, Tuple inbuilt functions.
Set: Creating a set, Python Set Operations, Python Built-in set methods.
Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the dictionary values, and
>>> 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 other
iterable 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:
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
changing single element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> 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
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
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)
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')
Sets
What is a Set?
– Example A = {x : x N, x < 5}
Some examples of Roster Form vs Set-builder Form
Roster Form Set-builder Form
1 {1, 2, 3, 4, 5} {x | x N, x <6}
Sets of Numbers
1. Natural Numbers (N)
• N = {1, 2, 3,4 ,5 6, 7, …}
2. Integers (Z)
• W = {0, 1, 2, 3, 4, 5, 6…}
• {𝑝 : p Z, q Z, q ≠ 0}
𝑞
Empty Set
• It is denoted by ϕ (phai)
• Also n (ϕ) = 0
Equal Sets
• i.e. A ⊆ A, B ⊆ B etc.
• i.e. ϕ ⊆ A, ϕ ⊆ B
• If A ⊆ B and B ⊆ A, then A = B
• Similarly, if A = B, then A ⊆ B and B ⊆ A
• The set of all possible subsets of a set A is called the power set of A,
denoted by P(A). IfA contains n elements, then P(A) = 2n sets.
• Let A be any set and let B be any non-empty subset. Then A is called
a proper subset ofB, and is written as A B, if and only if every
element of A is in B, and there exists at least one element in B
which is not there in A.
• i.e. if A = {1, 2}, B = {3, 4}, and C = {1, 5}, then U or = {1,
2, 3, 4, 5}
Operations on Sets
• Union of Sets
• So if A B = {x | x A or x B}
• Disjointed Sets
• Intersecting sets
• Two sets are said to be intersecting or overlapping or
joint sets, if they haveat least one element in common.
• Intersection of sets is
Associative
• (A B) C = A (B C)
• If A ⊆ B, then A B = A
• Since A ⊆ , so A = A
• A B ⊆ A and A B ⊆ B
• Difference of Sets
• If A B then A – B =
• Complement of a Set
• Please note
• ’ = and ’=
A A’ = and A A’ = ϕ
• A (B C) = (A B) (A C)
Say A = {1, 2}, B = {2, 3} and C = {3, 4}
• A (B C) = (A B) (A C)
Say A = {1, 2}, B = {2, 3} and C = {3, 4}
• De-Morgan’s Laws
• (A B)’ = A’ B’
A Set in Python is a collection of unique elements which are unordered and mutable.
Python provides various functions to work with Set. In this article, we will see a list of
all the functions provided by Python to deal with Sets.
❖
Dictionary is an unordered collection of elements. An element in
dictionary has a key: value pair.
❖
All elements in dictionary are placed inside the curly braces i.e. { }
❖
Elements in Dictionaries are accessed via keys and not by their position.
❖
The values of a dictionary can be any data type.
❖
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
❖ ❖ ❖
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical
❖
doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
❖ ❖
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.
❖
Dictionary is used
when data is being
constantly modified.
PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Difference between del and remove methods in List?
5. Difference between pop and remove in list?
6. How are the values in a tuple accessed?
7. What is a Dictionary in Python
8. Define list comprehension
9. Write a python program using list looping
10. Define Tuple and show it is immutable with an example.
11. state the difference between aliasing and cloning in list
12. what is list cloning
13. what is deep cloning
14. state the difference between pop and remove method in list
15. create tuple with single element
16. swap two numbers without using third variable
17. define properties of key in dictionary
18. how can you access elements from the dictionary
19. difference between delete and clear method in dictionary
20. What is squeezing in list? give an example
21. How to convert a tuple into list
22. How to convert a list into tuple
23. How can you return multiple values from function?
24. Find length of sequence without using library function.
25. how to pass tuple as argument
26. how to pass a list as argument
27. how can you insert values into dictionary
28. what is key value pair
29. mention different data types can be used in key and value
30. What is the use of from keys() in dictioanary.
PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix addition
8. write a program for matrix subtraction
9. Explain in detail about dictionaries and its methods.
10. Explain in detail about advanced list processing.