UNIT 5 - Mutable Data Structure
UNIT 5 - Mutable Data Structure
Mutable Data structure: Mutable data structure are those whose state can be
modified as per our need.
Definition of List:
❖ As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
❖ List is dynamic because based on our requirement we can increase the size and
decrease the size.
❖ In List the elements will be placed within square brackets and with comma separator.
❖ We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
❖ Python supports both positive and negative indexes. +ve index means from left to right
where as negative index means right to left.
Creation of List :
❖ Example:
❖ list=[]
❖ print(list)
❖ print(type(list))
❖ Output:
❖ []
❖ <class 'list’>
❖ Example:
P ag e |2
❖ list = [1, 2, 3, 4]
❖ print(list)
❖ print(type(list))
❖ Output:
❖ [1, 2, 3, 4]
❖ <class 'list’>
❖ Example:
❖ list=eval(input("Enter List:"))
❖ print(list)
❖ print(type(list))
❖ Output:
❖ [5, 6, 7, 8]
❖ <class 'list’>
[Note: eval is a built-in- function used in python, eval function parses the expression
argument and evaluates it as a python expression. In simple words, the eval function
evaluates the “String” like a python expression and returns the result as an integer.]
❖ Example 1:
❖ l=list(range(0,12,2))
❖ print(l)
❖ print(type(l))
❖ Output:
❖ [0, 2, 4, 6, 8,10]
❖ <class 'list'>
❖ Example 2:
❖ s=“arman"
P ag e |3
❖ l=list(s)
❖ print(l)
❖ print(type(l))
❖ Output:
❖ <class 'list'>
❖ Example:
❖ l=s.split()
❖ print(l)
❖ print(type(l))
❖ Output:
❖ <class 'list'>
List VS Mutability:
❖ Once we creates a List object, we can modify its content. Hence List objects are
mutable.
❖ Example:
❖ n=[10,20,30,40]
❖ print(n)
❖ n[1]=77
❖ print(n)
❖ Output:
❖ Example:
❖ print(list[0])
❖ print(list[-1])
❖ print(list[10])
❖ Output:
❖ 10
❖ 40
❖ Start: It indicates the Index where slice has to Start and Default Value is 0.
❖ Stop: It indicates the Index where slice has to End and Default Value is max allowed
Index of List ie Length of the List.
❖ Example:
❖ n=[1,2,3,4,5,6,7,8,9,10]
❖ print(n[2:7:2])
❖ print(n[4::2])
❖ print(n[3:7])
P ag e |5
❖ print(n[8:2:-2])
❖ print(n[4:100])
❖ Output:
❖ [3, 5, 7]
❖ [5, 7, 9]
❖ [4, 5, 6, 7]
❖ [9, 7, 5]
❖ [5, 6, 7, 8, 9, 10]
Loop List:
❖ Example:
❖ n = [0,1,2,3,4,5,6,7,8,9]
❖ i=0
❖ i=i+1
❖ Output:
❖ 0
❖ 1
❖ 2
❖ 3
❖ 4
❖ 5
❖ 6
❖ 7
❖ 8
❖ 9
P ag e |6
❖ Example:
❖ n=[0,1,2,3,4,5,6,7,8,9]
❖ for n1 in n:
❖ print(n1)
❖ Output:
❖ 0
❖ 1
❖ 2
❖ 3
❖ 4
❖ 5
❖ 6
❖ 7
❖ 8
❖ 9
❖ Example:
❖ l = ["A","B","C"]
❖ x = len(l)
❖ for i in range(x):
❖ print(l[i])
❖ Output:
❖ A
❖ B
❖ C
P ag e |7
❖ Example:
❖ n = [1, 2, 3, 4]
❖ print(len(n))
❖ Output:
❖ 4
(2) count(): It returns the number of occurrences of specified item in the list.
❖ Example:
❖ n=[1,2,2,2,2,3,3]
❖ print(n.count(1))
❖ print(n.count(2))
❖ print(n.count(3))
❖ print(n.count(4))
❖ Output:
❖ 1
❖ 4
❖ 2
❖ 0
(3) index(): Returns the index of first occurrence of the specified item.
❖ Example:
❖ n = [1, 2, 2, 2, 2, 3, 3]
❖ print(n.index(1))
❖ print(n.index(2))
❖ print(n.index(3))
❖ print(n.index(4))
P ag e |8
❖ Output:
❖ 0
❖ 1
❖ 5
❖ If the specified element is not present in the list then we will get ValueError.
❖ Hence before index() method we have to check whether item present in the list or not
by using in operator.
(4) append() Function: We can use append() function to add item at the end of the list.
❖ Example:
❖ list=[“M”,“N”]
❖ list.append("A")
❖ list.append("B")
❖ list.append("C")
❖ print(list)
❖ Output:
❖ Example:
❖ n=[1,2,3,4,5]
❖ n.insert(1,28)
❖ print(n)
❖ Output:
❖ [1, 28, 2, 3, 4, 5]
❖ If the specified index is greater than max index then element will be inserted at last
P ag e |9
position.
❖ If the specified index is smaller than min index then element will be inserted at first
position.
❖ Example:
❖ n=[1,2,3,4,5]
❖ n.insert(10,7)
❖ n.insert(-10,9)
❖ print(n)
❖ Output:
❖ [9, 1, 2, 3, 4, 5, 7]
(6) extend() Function: To add all items of one list to another list.
❖ Example 1:
❖ l1=[“Apple",“Mango"]
❖ l1.extend(l2)
❖ print(l1)
❖ Output:
❖ Example 2:
❖ l1 = [“Amit",“Sumit"]
❖ l1.extend(“kumar")
❖ print(l1)
❖ Output:
7) remove() Function: We can use this function to remove specified item from the list.
❖ If the item present multiple times then only first occurrence will be removed.
P a g e | 10
❖ Example:
❖ n=[1,2,1,3]
❖ n.remove(1)
❖ print(n)
❖ Output:
❖ [2, 1, 3]
❖ If the specified item is not present in list then we will get ValueError.
❖ Example:
❖ y=[10,20,10,30]
❖ y.remove(40)
❖ print(n)
❖ Output:
❖ Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
(8) pop() Function: It removes and returns the last element of the list.
❖ This is only function which manipulates list and returns some element.
❖ Example:
❖ n=[10,20,30,40]
❖ print(n.pop())
❖ print(n.pop())
❖ print(n)
❖ Output:
❖ 40
❖ 30
❖ [10, 20]
❖ Example:
❖ y = []
❖ print(y.pop())
❖ Output:
❖ In general we can use pop() function to remove last element of the list. But we can use
to remove elements based on index.
❖ Example:
❖ n = [10,20,30,40,50,60]
❖ print(n.pop())
❖ print(n.pop(1))
❖ print(n.pop(10))
❖ Output:
❖ 60
❖ 20
(9) clear() Function: We can use clear() function to remove all elements of List.
❖ Example:
❖ n=[1,2,3,4]
❖ print(n)
❖ n.clear()
❖ print(n)
❖ Output:
❖ [1, 2, 3, 4]
P a g e | 12
❖ []
❖ Example:
❖ n=[1,2,3,4]
❖ n.reverse()
❖ print(n)
❖ Output:
❖ [4, 3, 2, 1]
❖ If want to sort the elements of list according to default natural sorting order then we
should go for sort() method.
❖ Example 1:
❖ n = [2,5,15,1,0]
❖ n.sort()
❖ print(n)
❖ Output:
❖ [0,1,2,5,15]
❖ Example 2:
❖ s = ["D","B","C","A"]
❖ s.sort()
❖ print(s)
❖ Output:
❖ [“A","B","C",“D"]
❖ To use sort() function, compulsory list should contain only homogeneous elements.
Otherwise we will get TypeError.
P a g e | 13
❖ Example:
❖ n=[20,10,"A","B"]
❖ n.sort()
❖ print(n)
❖ Output:
❖ Example 1:
❖ n = [4,1,3,2]
❖ n.sort(reverse = True)
❖ print(n)
❖ Output:
❖ [4,3,2,1]
❖ Example 2:
❖ n = [4,1,3,2]
❖ n.sort(reverse = False)
❖ print(n)
❖ Output:
❖ [1,2,3,4]
(1) Concatenation Operator (+): We can use + to concatenate 2 lists into a single list.
❖ Example:
❖ a = [1, 2, 3]
❖ b = [4, 5, 6]
❖ c = a+b
P a g e | 14
❖ print(c)
❖ Output:
❖ [1, 2, 3, 4, 5, 6]
❖ To use + operator compulsory both arguments should be list objects, otherwise we will
get TypeError.
❖ Example:
❖ a = [1, 2, 3]
❖ b = a+[4]
❖ print(b)
❖ c = a+4
❖ print(c)
❖ Output:
❖ [1, 2, 3,4]
(2) Repetition Operator (*): We can use repetition operator * to repeat elements of list
specified number of times.
❖ Example:
❖ x = [1, 2, 3]
❖ y = x*3
❖ print(y)
❖ Output:
❖ [1, 2, 3, 1, 2, 3, 1, 2, 3]
❖ Whenever we are using comparison operators (==, !=) for List objects then the
following should be considered
❖ Example:
❖ print(x == y)
❖ print(x == z)
❖ print(x != z)
❖ Output:
❖ True
❖ False
❖ True
❖ Whenever we are using relaxational Operators (<, <=, >, >=) between List Objects,
only 1st Element comparison will be performed.
❖ Example 1:
❖ print(x>=y)
❖ print(x<y)
❖ print(x<=y)
❖ Output:
❖ True
❖ True
❖ False
❖ False
P a g e | 16
❖ Example 2:
❖ print(x>y)
❖ print(x>=y)
❖ rint(x<y)
❖ print(x<=y)
❖ Output:
❖ False
❖ False
❖ True
❖ True
❖ We can check whether element is a member of the list or not by using membership
operators.
❖ (1) in Operator
❖ Example:
❖ n=[10,20,30,40]
❖ print (10 in n)
❖ print (50 in n)
❖ Output:
❖ True
❖ False
P a g e | 17
❖ False
❖ True
❖ The process of giving another reference variable to the existing list is called aliasing.
❖ Example:
❖ x=[10,20,30,40]
❖ y=x
❖ print(x)
❖ print(y)
❖ Output:
❖ [10,20,30,40]
❖ [10,20,30,40]
❖ The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
❖ Example:
❖ x = [10,20,30,40]
❖ y=x
❖ y[1] = 777
❖ print(x)
❖ Output:
❖ [10,777,30,40]
❖ To overcome this problem, we should go for cloning. The process of creating exactly
duplicate independent object is called cloning.
❖ x = [10,20,30,40]
P a g e | 18
❖ y = x[:]
❖ y[1] = 777
❖ print(x)
❖ print(y)
❖ Output:
❖ [10,20,30,40]
❖ [10,777,30,40]
(2) By using copy() Function:
❖ x = [10,20,30,40]
❖ y = x.copy()
❖ y[1] = 777
❖ print(x)
❖ print(y)
❖ Output:
❖ [10,20,30,40]
❖ [10,777,30,40]
Nested Lists:
❖ Sometimes we can take one list inside another list. Such type of lists are called nested
lists.
❖ Example:
❖ n=[10,20,[30,40]]
❖ print(n)
❖ print(n[0])
❖ print(n[2])
❖ print(n[2][0])
❖ print(n[2][1])
P a g e | 19
❖ Output:
❖ 10
❖ [30, 40]
❖ 30
❖ 40
❖ Example:
❖ n=[[10,20,30],[40,50,60],[70,80,90]]
❖ print(n)
❖ for r in n:
❖ print(r)
❖ for i in range(len(n)):
❖ for j in range(len(n[i])):
❖ print(n[i][j],end=' ')
❖ print()
❖ Output:
❖ 10 20 30
❖ 40 50 60
❖ 70 80 90
List Comprehensions:
❖ It is very easy and compact way of creating list objects from any inerrable objects
(Like List, Tuple, Dictionary, Range etc) based on some condition.
❖ Example:
❖ print(s)
❖ print(v)
❖ m = [x for x in s if x%2==0]
❖ print(m)
❖ Output:
Definition Of Dictionary:
❖ Example:
❖ rollno -----name
Creation Of Dictionary:
❖ d = {} OR d = dict()
❖ Example:
❖ d = {}
❖ d[10]=“Lucky"
❖ d[20]=“Arman"
❖ d[30]=“Dhairya"
❖ print(d)
❖ Output:
❖ Example:
❖ d = {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ print(d[10])
❖ print(d[20])
❖ print(d[40])
P a g e | 22
❖ Output:
❖ Lucky
❖ Arman
❖ KeyError: 40
❖ We can prevent this by checking whether key is already available or not by using in
operator.
❖ Example:
❖ d = {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ if 40 in d:
❖ print(d[40])
❖ d[key] = value
❖ If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair.
❖ If the key is already available then old value will be replaced with new value.
❖ Example:
❖ d = {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ print(d)
❖ d[40]=“Sumit"
❖ print(d)
❖ d[10]=“Sunny"
❖ print(d)
❖ Output:
❖ {10:’Lucky',20:’Arman', 30:’Dhairya’}
(1) del d[key]: It deletes entry associated with the specified key.
❖ Example:
❖ d= {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ print(d)
❖ del d[10]
❖ print(d)
❖ del d[40]
❖ Output:
❖ {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ KeyError: 40
❖ Example:
❖ d= {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ print(d)
❖ d.clear()
❖ print(d)
❖ Output:
❖ {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ {}
❖ Example:
❖ d= {10:’Lucky',20:’Arman', 30:’Dhairya’}
❖ print(d)
P a g e | 24
❖ del d
❖ print(d)
❖ Output:
❖ {10:’Lucky',20:’Arman', 30:’Dhairya’}
Dictionary Comprehension:
❖ It is very easy and compact way of creating objects from any inerrable objects (Like
List, Tuple, Dictionary, Range etc) based on some condition.
❖ Example:
❖ print(squares)
❖ print(doubles)
❖ Output:
❖ {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
❖ d = dict([(10,“Lucky"),(20,“Arman"),(30,“Dhairya")]):
❖ d1 = d.copy()
P a g e | 25
(5) update():
❖ d.get(key): If the key is available then returns the corresponding value otherwise
returns None. It won’t raise any error.
❖ Example:
❖ d={10:“Lucky",20:“Arman",30:“Dhairya"}
❖ print(d[10])
❖ print(d.get(10))
❖ print(d.get(40))
❖ print(d.get(10,"Guest"))
❖ print(d.get(40,"Guest"))
❖ Output:
❖ Lucky
❖ Lucky
❖ None
❖ Lucky
❖ Guest
(7) popitem(): It removes an arbitrary item(key-value) from the dictionary and returns it.
❖ Example:
❖ d={10:“Lucky",20:“Arman",30:“Dhairya"}
❖ print(d)
❖ print(d.popitem())
❖ print(d)
P a g e | 26
❖ d={}
❖ print(d.popitem())
❖ Output:
❖ {10:“Lucky",20:“Arman",30:“Dhairya"}
❖ (30, ‘Dhairya’)
❖ Example:
❖ d={10:“Lucky",20:“Arman"}
❖ print(d.keys())
❖ for k in d.keys():
❖ print(k)
❖ Output:
❖ dict_keys([10, 20])
❖ 10
❖ 20
❖ Example:
❖ d= {10:“Lucky",20:“Arman",30:“Dhairya"}
❖ print(d.values())
❖ for v in d.values():
❖ print(v)
❖ Output:
❖ Lucky
P a g e | 27
❖ Arman
❖ Dhairya
❖ Example:
❖ d= {10:“Lucky",20:“Arman",30:“Dhairya"}
❖ Output:
❖ 10 -- Lucky
❖ 20 -- Arman
❖ 30 -- Dhairya
(10) setdefault():
❖ d.setdefault(k,v): If the key is already available then this function returns the
corresponding value.
❖ If the key is not available then the specified key-value will be added as new item to the
dictionary.
❖ Example:
❖ d= {10:“Lucky",20:“Arman",30:“Dhairya"}
❖ print(d.setdefault(40,"pavan"))
❖ print(d)
❖ print(d.setdefault(10,"sachin"))
❖ Output:
❖ pavan
❖ Lucky
fromkeys() function returns the dictionary with key mapped and specific value. It creates a
new dictionary from the given sequence with the specific value.
seq = ('a', 'b', 'c')
print(dict.fromkeys(seq, None))
P a g e | 28
Output:
{'a': None, 'b': None, 'c': None}
Example:
seq = {'a', 'b', 'c', 'd', 'e'}
# creating dict with default values as None
res_dict = dict.fromkeys(seq)
print("The newly created dict with None values : " + str(res_dict))
# creating dict with default values as 1
res_dict2 = dict.fromkeys(seq, 1)
OUTPUT:
The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]}
The dict with list values after appending : {'d': [2, 3, 4], 'e': [2, 3, 4], 'c': [2, 3, 4], 'a': [2, 3, 4],
'b': [2, 3, 4]}
Definition Of Set:
❖ If we want to represent a group of unique values as a single entity then we should go
for set.
❖ Set objects are mutable i.e once we creates set object we can perform any changes in
that object based on our requirement.
❖ We can represent set elements within curly braces and with comma separation.
❖ We can apply mathematical operations like union, intersection, difference etc on set
objects.
Creation Of Set:
❖ Example:
❖ s={10,20,30,40}
❖ print(s)
❖ print(type(s))
❖ Output:
❖ <class 'set'>
❖ s = set(any sequence)
❖ Example 1:
❖ l = [10,20,30,40,10,20,10]
❖ s=set(l)
❖ print(s)
❖ Output:
❖ s=set(range(5))
❖ print(s)
❖ Output:
❖ {0, 1, 2, 3, 4}
❖ Example 1:
❖ s={}
❖ print(s)
❖ print(type(s))
❖ Output:
❖ {}
❖ <class 'dict'>
❖ Example 2:
❖ s=set()
❖ print(s)
❖ print(type(s))
❖ Output:
❖ set()
❖ <class 'set'>
❖ x.union(y): We can use this function to return all elements present in both sets.
❖ x.union(y) OR x|y.
❖ Example:
❖ print (x.union(y))
❖ print (x|y)
❖ Output:
P a g e | 31
❖ (2) intersection():
❖ print (x.intersection(y))
❖ print(x&y)
❖ Output:
❖ {40, 30}
❖ {40, 30}
❖ (3) difference():
❖ Example:
❖ x = {10, 20, 30, 40}
❖ print (x.difference(y))
❖ print (x-y)
❖ print (y-x)
❖ Output:
❖ {10, 20}
❖ {10, 20}
❖ {50, 60}
❖ (4) symmetric_difference():
❖ Example:
P a g e | 32
❖ print (x.symmetric_difference(y))
❖ print(x^y)
❖ Output:
❖ We can check whether element is a member of the list or not by using memebership
operators.
❖ (1) in Operator
❖ (2) not in Operator
❖ Example:
❖ s=set("durga")
❖ print(s)
❖ print('d' in s)
❖ print('z' in s)
❖ Output:
❖ True
❖ False
❖ Example:
❖ s={10,20,30}
❖ s.add(40)
❖ print(s)
P a g e | 33
❖ Output:
❖ Arguments are not individual elements and these are Inerrable objects like List, Range
etc.
❖ All elements present in the given Iterable objects will be added to the set.
❖ Example:
❖ s={10,20,30}
❖ l=[40,50,60,10]
❖ s.update(l,range(5))
❖ print(s)
❖ Output:
❖ It is cloned object.
❖ Example:
❖ s = {10,20,30}
❖ s1 = s.copy()
❖ print(s)
❖ print(s1)
❖ Output:
❖ {10,20,30}
❖ {10,20,30}
(4) pop():It removes and returns some random element from the set.
❖ Example:
❖ s={40,10,30,20}
❖ print(s)
P a g e | 34
❖ print(s.pop())
❖ print(s)
❖ Output:
❖ 40
❖ {10, 20, 30}
❖ If the specified element is not present in the Set then we will get KeyError.
❖ Example:
❖ s.remove(30)
❖ print(s)
❖ s.remove(50)
❖ Output:
❖ KeyError: 50
(6) discard(x):
❖ If the specified element not present in the set then we won't get any error.
❖ Example:
❖ s.discard(10)
❖ print(s)
❖ s.discard(50)
❖ print(s)
❖ Output:
P a g e | 35
❖ {20, 30}
❖ {20, 30}
❖ Example:
❖ s={10,20,30}
❖ print(s)
❖ s.clear()
❖ print(s)
❖ Output:
❖ set()
Set Comprehension:
❖ It is very easy and compact way of creating objects from any inerrable objects (Like
List, Tuple, Dictionary, Range etc) based on some condition.
❖ print (s)
❖ print (s)
❖ Output:
❖ {0, 1, 4, 9, 16}
lambda Function:
❖ Sometimes we can declare a function without any name, such type of nameless
functions are called anonymous functions or lambda functions.
❖ return n*n
❖ lambda n:n*n
P a g e | 37
❖ By using Lambda Functions we can write very concise code so that readability of the
program will be improved.
❖ s=lambda n:n*n
❖ Output:
❖ The Square of 4 is : 16
❖ The Square of 5 is : 25
❖ s=lambda a,b:a+b
❖ Output:
❖ Lambda Function internally returns expression value and we are not required to write
return statement explicitly.
❖ For every element present in the given sequence, apply some functionality and
generate new element with the required modification.
❖ Eg: For every element present in the list perform double and generate new list of
doubles.
P a g e | 38
❖ The function can be applied on each element of sequence and generates new sequence.
Program to double the Numbers from the List by using map() Function (Without
Lambda Function):
❖ l=[1,2,3,4,5]
❖ def doubleIt(x):
❖ return 2*x
❖ l1=list(map(doubleIt,l))
❖ print(l1)
❖ Output:
❖ [2, 4, 6, 8, 10]
Program to double the Numbers from the List by using map() Function(With Lambda
Function):
❖ l=[1,2,3,4,5]
❖ l1=list(map(lambda x:2*x,l))
❖ print(l1)
❖ Output:
❖ [2, 4, 6, 8, 10]
❖ We can apply map() function on multiple lists also. But make sure all list should have
same length.
❖ Example:
❖ l1=[1,2,3,4]
❖ l2=[2,3,4,5]
❖ l3=list(map(lambda x,y:x*y,l1,l2))
❖ print(l3)
❖ Output:
P a g e | 39
reduce() Function:
❖ reduce() function reduces sequence of elements into a single element by applying the
specified function.
❖ Syntax: reduce(function,sequence)
❖ reduce() function present in functools module and hence we should write import
statement.
Program to add and multiply all the Numbers of the List by using reduce()
Function(With Lambda Function):
❖ l=[10,20,30,40,50]
❖ sum=reduce(lambda x,y:x+y,l)
❖ print(sum)
❖ mul=reduce(lambda x,y:x*y,l)
❖ print(mul)
❖ Output:
❖ 150
❖ 12000000
filter() Function:
❖ filter() Function: We can use filter() function to filter values from the given sequence
based on some condition.
❖ filter(function,sequence): Where Function Argument is responsible to perform
conditional check and sequence can be List OR Tuple OR String.
Program to filter only Even Numbers from the List by using filter() Function(Without
Lambda Function):
❖ def isEven(x):
❖ if x%2==0:
❖ return True
P a g e | 40
❖ else:
❖ return False
❖ l=[0,5,10,15,20,25,30]
❖ l1=list(filter(isEven,l))
❖ print(l1)
❖ Output:
❖ [0,10,20,30]
Program to filter only Even Numbers from the List by using filter() Function(With
Lambda Function):
❖ l=[0,5,10,15,20,25,30]
❖ l1=list(filter(lambda x:x%2==0,l))
❖ print(l1)
❖ Output:
❖ [0,10,20,30]
1. Write a Python program to find the sum of all the elements in the list.
❖ Solution:
❖ total = 0
❖ Output:
2. Write a Python program to add two given lists using map and lambda.
❖ Solution:
❖ nums 1 = [0, 1, 2]
P a g e | 41
❖ nums 2 = [3, 4, 5]
❖ print("Original list:")
❖ print(nums1)
❖ print(nums2)
❖ print(list(result))
❖ Output:
❖ Original list:
❖ [0, 1, 2]
❖ [3, 4, 5]
❖ [3, 5, 7]
❖ Solution:
❖ return(dict2.update(dict1))
❖ dict1 = {'a': 10, 'b': 8}
❖ print(Merge(dict1,dict2))
❖ print(dict2)
❖ Output:
❖ None
4. Write a Python program to print the even numbers from a given list.
❖ l = [12,45,67,89,123]
❖ for i in l:
❖ if i%2 == 0:
P a g e | 42
❖ print(i)
❖ else:
❖ pass
5. Write a Python Program to print the largest even and largest odd number in a list.
❖ l = [12,45,67,89,123]
❖ for i in range(len(l)):
❖ if l[i] %2 == 0:
❖ maxe = l[i]
❖ if l[i] %2 == 1:
❖ maxo = l[i]
❖ for i in range(len(l)):
❖ if l[i] >= maxe and l[i]%2 == 0:
❖ maxe = l[i]
❖ if l[i] >= maxo and l[i]%2 == 1:
❖ maxo = l[i]
❖ print(maxe)
❖ print(maxo)
6. Write a Python program to swap first and last element of the list.
❖ l = [12,45,67,89,123]
❖ count = 0
❖ for i in l:
❖ count = count + 1
❖ temp = l[0]
❖ l[0] = l[count-1]
❖ l[count-1] = temp
❖ print(l)
❖ def reverse(l):
❖ return l[::-1]
❖ newlist = eval(input("Enter list : "))
❖ print(reverse(newlist))
for i in newlist:
sum = sum+ i
return sum
print(s(l))
P a g e | 44
fromkeys() function returns the dictionary with key mapped and specific value. It creates a
new dictionary from the given sequence with the specific value.
seq = ('a', 'b', 'c')
print(dict.fromkeys(seq, None))
Output:
{'a': None, 'b': None, 'c': None}
Example:
seq = {'a', 'b', 'c', 'd', 'e'}
# creating dict with default values as None
res_dict = dict.fromkeys(seq)
print("The newly created dict with None values : " + str(res_dict))
# creating dict with default values as 1
res_dict2 = dict.fromkeys(seq, 1)
OUTPUT:
The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]}
The dict with list values after appending : {'d': [2, 3, 4], 'e': [2, 3, 4], 'c': [2, 3, 4], 'a': [2, 3, 4],
'b': [2, 3, 4]}
print (list(enumerate(s1)))
OUTPUT:
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]
[(0, 'g'), (1, 'e'), (2, 'e'), (3, 'k')]