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

Unit - 4 (Python)

The document provides an overview of lists in Python, detailing their characteristics, operations, and methods. It explains list manipulation techniques such as concatenation, slicing, and various built-in functions, as well as mutability and cloning of lists. Additionally, it covers how to pass lists as parameters to functions and includes an example of removing duplicates from a list.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

Unit - 4 (Python)

The document provides an overview of lists in Python, detailing their characteristics, operations, and methods. It explains list manipulation techniques such as concatenation, slicing, and various built-in functions, as well as mutability and cloning of lists. Additionally, it covers how to pass lists as parameters to functions and includes an example of removing duplicates from a list.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lists

• List is a sequence of values.

• String is also sequence of values. But in string this sequence is of characters. On


the other hand, in case of List the values can be of any type.

• The values in the list are called elements or items. These elements are separated
by commas and enclosed within the square bracket.

For example

(10,20,30,40] # list of integers

['aaa','bbb','ccc'] #list of strings

['a',10,20,'b',33.33] #mixed list

[10,20,['a','b','d']] #nested list

• The list within another list is called nested list.

• The list that contains no element is called empty list. The empty list is
represented

by []

1. List Operations
There are two operations that can be performed using operators such as + and *

1. Concatenation using +

The two lists can be created and can be joined using + operator. Following
screenshot illustrates it.
2. Repetition using *

The * is used to repeat the list for number of times. Following screenshot illustrates
it.

2. List Slices
•The : operator used within the square bracket that it is a list slice and not the index
of the list

>>> a=[10,20,30,40,50,60]

>>> a[1:4]

[20, 30, 40]

>>> a[:5]

[10, 20, 30, 40, 50)

>>> a[4]

[50]
>>> a[:]

[10, 20, 30, 40, 50, 60]

>>>

• If we omit the first index then the list is considered from the beginning. And if we
omit the last second index then slice goes to end.

• If we omit both the first and second index then the list will be displayed from the
beginning to end.

• Lists are mutable. That means we can change the elements of the list. Hence it is
always better to make a copy of the list before performing any operation.

• For example

>>> a=[10,20,30,40,50]

>>> a[2:4]=[111,222,333]

>>> a

[10, 20, 111, 222, 333, 50)

>>>

3. List Methods
List Methods

1) append(): This method is to add the element at the last position of the list.

Syntax :

[Link](element)

Example :

>>> a=[10,20,30]

>>> [Link](40) #adding element 40 at the end


>>> a

[10, 20, 30, 40]

>>> b=['A', 'B', 'C']

>>> [Link]('D') #adding element D at the end

>>> b

['A', 'B', 'C', 'D')

>>>

2) extend(): The extend function takes the list as an argument and appends this list
at the end of old list.

Syntax :

[Link](List2)

Where List2 is added at the end of List1

Example :

>>> a={10,20,30]

>>> b=['a','b', 'c']

>>> [Link](b)

>>> a

[10, 20, 30, 'a', 'b', 'c']

>>>

3) insert(): This function allows to insert the desired element at specified position.

Syntax :

[Link](position, element)

Where the first parameter is a position at which the element is to be inserted. The
element to be inserted is the second parameter in this function.
Example :

a=[10,20,30]

[Link](2,25)

print("List a = ",a)

Output will be

List a = [10, 20, 25, 30)

>>>

4) pop() :

This function removes the element specified by the index.

Syntax :

[Link](index)

The index represent the location of element in the list and the element specified by
the index will be deleted and returned. The parameter passed to the list is optional.
If no parameter is passed, the default index -1 is passed as an argument which
returns the last element.

Example

#list created

a=[10,20,30,40,50]

ret_val=[Link](2)

print("The deleted element is = ",ret_val)

print("The modified list is = ",a)

Output

The deleted element is = 30

The modified list is = [10, 20, 40, 50)


>>>

Pop when no parameter is passed

Syntax

[Link]()

Example

#list created

a = [10,20,30,40,50]

ret_val=[Link]()

print("The deleted element is = ",ret_val)

print("The modified list is = ",a)

Output

The deleted element is = 50

The modified list is = [10, 20, 30, 40)

Pop() when negative parameter is passed

Syntax

[Link](negative index)

Example

# Creation of list

a = [10,20,30,40,50]

# When -1 is passed

# Pops Last Element

print("\nWhen -1 is passed:')

print('Return Value:', [Link](-1))


print('Updated List:', a)

# When -3 is passed

# Pops Third Last Element

print("\nWhen -3 is passed:')

print('Return Value: ', [Link](-3))

print('Updated List:', a)

Output

When -1 is passed:

Return Value: 50

Updated List: [10, 20, 30, 40]

When -3 is passed:

Return Value: 20

Updated List: [10, 30, 40]

>>>

5) remove : The remove method deletes the element which is passed as a


parameter. It actually removes the first matching element.

Syntax :

[Link](element)

Example :

>>> a=[10,20,30,20,40,50]

>>> [Link](20)
>>> print(a)

[10, 30, 20, 40, 50]

6) erase(): This method erases all the elements of the list. After this operation the
list becomes empty.

Syntax :

[Link]()

Example :

>>> a=[10,20,30,40,50]

>>> [Link]()

>>> print(a)

>>>

7) del(): This method deletes all the elements within the given range.

Syntax :

[Link](a:b)

The element within the range a to b get deleted by this method.

Example :

>>> a=['a','b','c','d', 'e']

>>> del a[2:4]

>>> a

['a', 'b', 'e']

>>>

8) sort(): This method sorts or arranges the elements in increasing order

Syntax:
[Link]()

Example :

>>> a=['x', 'z','u','v','y','w']

>>> [Link]()

>>> a

['u', 'v', 'w', 'x', 'y', 'z']

>>>

9) reverse(): This method is for reversing the elements in the list.

Syntax :

[Link]()

Example :

>>> a=[10,20,30,40,50]

>>> [Link]()

>>> print("List after reversing is: ",a)

List after reversing is: [50, 40, 30, 20, 10]

>>>

10) count(): This method returns a number for how many times the particular
element appears in the list.

Syntax :

[Link](element)

Example :

>>> a=[10,20,10,30,10,40,50]

>>> print("Count for element 10 is:",[Link](10))


Count for element 10 is: 3

Built-in Functions For List

1) all() : This function returns true if all the elements of the list are true or if the list
is empty.

Syntax :

all(iterable)

The all method returns true if all elements in iterable are true otherwise it returns
false.

Example :

>>> a=[1,2,3,4] >>>

print(all(a))

True

>>> b=[1,2,0,3,4]

>>> print(all(b))

False

>>> c=[l]

>>> print(all(c))

True

>>>

2) any(): This method returns True if any element of an iterable is true. If not, this
method returns False.

Syntax :

any(iterable)

The any method returns:


True if at least one element of an iterable is true

False if all elements are false or if an iterable is empty

When : Retum Value

All values are true: True

All values are false: False

One value is true (others are false): True

One value is false (others are true): True

Empty Iterable: False

Example:

>>> a=[10,0,20,30,40]

>>> print(any(a))

True

>>> b=[ ]

>>> print(any(b))

False

>>> c=[False]

>>>print(any(c))

False

>>>

3) len(): This function returns the number of items present in the list

Syntax :

len(List)

Example :
>>> a=[10,20,30,40,50]

>>> print("The length of list a is: ",len(a))

The length of list a is: 5

>>>

4) list(): This function converts an iterable to a list

Syntax :

list([iterable])

The list() constructor returns a mutable sequence list of elements.

If no parameters are passed, it creates an empty list.

If iterable is passed as parameter, it creates a list of elements in the iterable.

Example :

>>>print(list())

[]

>>> mystr="hello"

>>> print(list(mystr))

['h', 'e', 'l', 'l', 'o']

>>> mytuple=('h', 'e', 'l', 'l', 'o')

>>> print(list(mytuple))

['h', 'e', 'l', 'l', 'o']

>>>

5) max(): This function returns the maximum value element from the list.

Syntax :

max(iterable)
The maximum value from the iterable is returned.

Example :

>>> a=[1,2,3,55,7]

>>>print(max(a))

55

>>>

6) min(): This function returns the minimum value element from the list.

Syntax :

min(iterable)

The minimum value from the iterable is returned.

Example:

>>> a=[100,10,1,20,30]

>>>print(min(a))

>>>

7) sum(): This function adds the items of iterable and the sum is returned.

Syntax :

Sum(iterable, start)

The sum of all the elements from the iterable is returned. The start is optional. If
start value is mentioned then it is added to the sum.

Example :

>>> a=[1,2,3,4]

>>> result=sum(a)
>>> print(result)

10

>>>

start=100

>>> print(sum(a,start))

110

>>>

4. List Loop
The Loop is used in list for traversing purpose. The for loop is used to traverse the
list elements

Syntax

for VARIABLE in LIST :

BODY

Example

>>> a=['a','b','c','d', 'e'] # List a is created

>>> for i in a:

>>> print(i)

will result into

d
e

>>>

If me want to update the elements of the list, then we must pass index as argument
to for loop. For example

>>> a=[10,20,30,40]

>>> for i in range(len(a)):

a[i] = a[i]+1 #incremented each number by one

>>> print(a)

[11, 21, 31, 41]

>>>

5. Mutability
• Strings are immutable. That means, we cannot modify the strings. But Lists are
mutable. That means it is possible to change the values of list.

• If the bracket operator is present on the left hand side, then that element is
identified and the list element is modified accordingly.

For example

>>> a=['AAA','BBB','CCC')

>>> a[1]='XXX

>>> a

['AAA', 'XXX', 'CCC')

>>>

Using the in operator we can check whether particular element belongs to the list
or not. If the given element is present in the list it returns True otherwise False. For
example

>>> a = ('AAA', 'XXX', 'CCC')


>>> 'XXX' in a

True

>>> 'BBB' in a

False

>>>

6. Aliasing
Definition: An object with more than one reference has more than one name, so
we say that the object is aliased.

For example -

>>> x = [10,20,30]

>>> y = x

>>> y is x

True

>>> y

[10, 20, 30]

>>>

The association of a variable with object is called reference.

In above example, reference y is created using object a. Diagrammatically aliasing


is shown in Fig. 4.1.1.
If any change is made in one reference then other object gets affected. For example

>>> x=[10,20,30]

>>> y = x

>>> y

[10, 20, 30]

>>> y[0]=111

>>>y

[111, 20, 30]

>>> x

[111, 20, 30]

>>>

Note that in above list if we change the reference list y then the list x also gets
changed automatically

7. Cloning Lists
Cloning means creating exact replica of the original list. There are various method
using which we can clone the list.

1. Cloning by assignment

We can assign one list to another new list. This actually creates a new reference to
the original list.

For example

>>> a=['a', 'b', 'c']

>>> b = a

>>> b
['a', 'b', 'c']

>>>

Note that here list bit a clone of original list a. But as the reference is created
change in one list causes change in another list.

2. Cloning by slicing

We can create a clone by slicing. During this process, [:] operator is used for
creating the clone. For example

>>> a = [10,20,30]

>>> b = a[:]

>>> print(" List a =",a)

List a = [10, 20, 30]

>>> print(" List b=",b)

List b= [10, 20, 30]

>>> b[1]=222

>>> print("List b= ",b)

List b= [10, 222, 30]

>>> print("List a="/a)

List a= [10, 20, 30]

>>>

Note that the clone b is created from the list a. But change in one list does not
affect the other list

The operator [:] means copy the elements in one list from beginning to end into
another list.

3. Clone by copy constructor


We can create a clone for the list using copy constructor. This is just similar to
clone by slicing. The list function is used to create the clone. For example

>>> a = ['A','B','C']

>>> b = list(a)

>>> b

['A', 'B', 'C']

>>> a

['A', 'B', 'C']

>>>

Note that even if we make changes in the clone list, the other list does not get
changed. For example

>>> a

['A', 'B', 'C']

>>> b[1]='Z

>>> b

['A', 'Z', 'C')

>>> a

['A', 'B', 'C']

>>>

8. List Parameters
A list can be passed as a parameter to the function. This parameter is passed by
reference. That means any change made in the list inside the function will affect
the list even after returning the function to the main.
For example :

In above screen-shot, the python code is written in interactive mode. The


function Insert_End is for inserting the element at the end of the list.

Here we pass the list a as parameter to the function. Inside the function, the
element is added at the end of the list. Hence after the making call to the function,
we get the list in which the element is inserted at the end.

Example 4.1.1 Write a Python program to remove duplicates from a list

1. seen — meaning and use

seen is usually a set that stores all elements you have already encountered in a
loop.

Why use a set?

 Fast lookup (O(1) time)


 Avoids repeated values

Syntax example:

 seen = set() # empty set


 for x in a:
 if x not in seen:
 [Link](x) # mark x as "seen"

2. duplicates — meaning and use

duplicates is another set that stores elements that appear more than once in the
list.

Syntax example:

 duplicates = set()
 for x in a:
 if x in seen:
 [Link](x) # x is repeated

Solution :

a = [1,2,3,2,1,4,5,4,8,5,4]
duplicates = set()
#seen=set()
for x in a:
if x not in duplicates:
[Link](x)
print(duplicates)

Output
{1, 2, 3, 4, 5, 8}

a = [1,2,3,2,1,4,5,4,8,5,4]
duplicates = set()
seen=set()
for x in a:
if x in seen:
[Link](x)
else:
[Link](x)
print(duplicates)
print(seen)

Output:
{1, 2, 4, 5}
{1, 2, 3, 4, 5, 8}

Example 4.1.2 Write a Python program to read a list of words and return the
length of longest one

Solution :

a=[]
print("Enter the number of words in list:")
n = int(input())

for i in range(0,n):
item = input("Enter word" + str(i+1) + ":")
[Link](item)
max_len = len(a[0])
temp = a[0]
for i in a:
if(len(i) > max_len):
max_len = len(i)
temp = i
print("The longest length word is ")
print(temp)

Example 4.1.3 Write a Python program to print the maximum among 'n' randomly
generate 'd numbers by storing them in a list.

Solution:

import random
def Max_from_random(s,e,n):
ran = []
for i in range(n):
[Link]([Link](s, e))
print("The generated numbers are: ",ran)
max_num = ran[0]
for ele in ran:
if(ele>max_num):
max_num = ele
return max_num
# Driver Code
n = int(input("How many random numbers want to display::"))
s = int(input("Enter Starting number ::"))
e = int(input("Enter Ending number ::"))
print(Max_from_random(s, e, n))

Output

How many Random Numbers want to disaply ::10

Enter Starting number ::1

Enter Ending number ::10

The generated numbers are: [8, 2, 4, 9, 7, 4, 2, 6, 8, 5]

>>>

Example 4.1.4 Write a Python program to rotate a list by right n times with and
without slicing technique.

Solution :

arr1 = [1, 2, 3, 4, 5]
print("Original List : " + str(arr1))
print("Rotating a list by 3 using slicing technique")
arr1 = arr1[-3:] + arr1[:-3]
print(arr1)
arr2 = [11,22,33,44,55]
print("Original List : " + str(arr2))
n=3
print("Rotating a list by 3 without using slicing technique")
for i in range(0,n):
last = arr2[len(arr2)-1]
for j in range (len(arr2)-1,-1,-1):
#shift element of array by one
arr2[j] = arr2[j-1]
arr2[0] = last
print(arr2)
Output

Original List : [1, 2, 3, 4, 5]

Rotating a list by 3 using slicing technique

[3, 4, 5, 1, 2]

Original List : [11, 22, 33, 44, 55]

Rotating a list by 3 without using slicing technique

[33, 44, 55, 11, 22]

Review Questions

1. Discuss different options to traverse a list.

2. Demonstrate the working of +, * and slice operators in python.

3. How will you update list items? Give one example.

4. Compare lists and arrays with example. Can list be considered as an array?
Justify.
Tuples
Tuple is a sequence of values. It is similar to list but there lies difference between
tuple and list

Difference between Tuple and List

Tuple

1. Tuple use parenthesis

2. Tuples can not be change

List

1. List use square brackets

2. Lists can be changed.

Tuple is said to immutable. That means once created we can not change the tuple.

Examples of tuples

T1 = (10,20,30,40)

T2 = (-a', 'b','c','d')

T3 = (‘A’,10,20)

T4 = ('aaa','bbb’,30,40)

The empty tuple can be created as

T1 = ( )

How to Write Tuple?

Tuple is written within the parenthesis. Even if the tuple contains a single value,
the comma is used as a separator. For example -

T1 = (10)

The tuple index starts at 0. For example


>>> t1 = (10,20, 'AAA','BBB')

>>> print(t1[0])

10 >>> print(t1[1:3])

(20, 'AAA')

>>>

1. Tuple Assignment
• We can create a tuple by using assignment operator. Multiple assignments are
possible at a time using tuple assignment. For example –

>>> a,b=10,20

>>> print(a)

10

>>> print(b)

20

>>>

• Here the left side is a tuple of variables; the right side is a tuple of expressions.

• Each value is assigned to its respective variable.

• All the expressions on the right side are evaluated before any of the assignments.

• Note that the number of variables on the left and right have to be the same.

• We can also separate out the values in the expression in the tuple by using the
split function. For example

>>> student = 'AAA, 123'

>>> name, roll = [Link](',').


>>> print(name)

AAA

>>> print(roll)

123

>>>

• In above example, the expression is split at comma and the two separated values
are collected in two different variables. We have name and roll variables in which
the corresponding values are stored.

2. Tuple as Return Value


Normally function return a single value, but if the value is tuple, then multiple
values can be returned.

For example -

[Link]

def student_Info():

name= ‘AAA’

roll=101

return name,roll

Output
3. Variable Number of Arguments
In python, it is possible to have variable number of arguments. In that case the
parameter name begins with *. Then these variable number of arguments are
gathered into a tuple. For example -

[Link]

def student_Info(*args):

print(args)

Output

In above program * accepts the variable number of arguments and inside the
function definition, these arguments are printed.

Review Questions

1. Can function return tuples? If yes give example.

2. Demonstrate with code the various operations that can be performed on tuples.

3. Compare and contrast tuples and lists in Python.

4. What is tuple in Python? How does it differ from list?


Dictionaries
Definition : In Python, dictionary is unordered collection of items. These items are
in the form of key-value pairs.

• The dictionary contains the collection of indices called keys and collection of
values.

• Each key is associated with a single value.

• The association of keys with values is called key-value pair or item.

• Dictionary always represent the mappings of keys with values. Thus each key
maps to a value.

How to Create Dictionary?

• Items of the dictionary are written within the {} brackets and are separated by
commas

• The key value pair is represented using: operator. That is key:value

• The keys are unique and are of immutable types - such as string, number, tuple.

• We can also create a dictionary using the word dict( ). For example –
>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue'})

How to access the elements in dictionary ?

We can access the element in the dictionary using the keys. Following script
illustrates it

[Link]

1. Operations and Methods


Basic operations

Various operations that can be performed on dictionary are:

1. Adding item to dictionary

We can add the item to the dictionary. For example


>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue'})

>>> print(my_dictionary)

{0: 'Red', 1: 'Green', 2: 'Blue'}

>>> my_dictionary[3] = 'Yellow' #adding the element to the dictioary

>>> print(my_dictionary)

{0: 'Red', 1: 'Green', 2: 'Blue', 3: 'Yellow'}

>>>

2. Remove item from dictionary

For removing an item from the dictionary we use the keyword del. For example

>>> del my_dictionary[2] #deleting the item from dictionary

>>> print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Green', 3: 'Yellow'}

>>>

3. Updating the value of the dictionary

We can update the value of the dictionary by directly assigning the value to
corresponding key position. For example -

>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue')) #creation of dictionary

>>> print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Green', 2: 'Blue'}

>>> my_dictionary[1]='Yellow' #updating the value at particular index

>>>print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Yellow', 2: 'Blue'} #updation of value can be verified.

>>>
4. Checking length

The len() function gives the number of pairs in the dictionary. For example

>>> my_dictionary=dict({0:'Red', 1:'Green',2:'Blue'}) #creation of dictionary

>>> len(my_dictionary) # finding the length of dictionary

3 #meaning - that there are 3 items in dictionary

>>>

Methods in dictionary

Following are some commonly used methods in dictionary.


1. The clear method
This method removed all the items from the dictionary. This method does
not take any parameter and does not return anything. For example

>>> my_dictionary={1:'AAA',2:'BBB',3: CCC'} # creation of dictionary

>>> print(my_dictionary) #display

{1: 'AAA', 2: 'BBB', 3: 'CCC"}

>>> my_dictionary.clear() #using clear method

>>> print(my_dictionary) #display

{}

>>>

2. The copy method

The copy method returns the copy of the dictionary. It does not take any parameter
and returns a shallow copy of dictionary. For example

>>> my_dictionary={1:'AAA',2:'BBB',3:"CCC"}

>>> print(my_dictionary)

{1: 'AAA', 2: 'BBB', 3: CCC'}

>>> new_dictionary=my_dictionary.copy()

>>> print(new_dictionary)

{1: 'AAA', 2: 'BBB', 3: 'CCC'}

>>>

3. The fromkey method

The fromkeys() method creates a new dictionary from the given sequence of
elements with a value provided by the user.

Syntax

[Link](sequences, value])
The fromkeys() method returns a new dictionary with the given sequence of
elements as the keys of the dictionary. If the value argument is set, each element of
the newly created dictionary is set to the provided value.

For example

>>> keys = {10,20,30}

>>> values = 'Number'

>>> new_dict = [Link](keys,values)

>>> print(new_dict)

{10: 'Number', 20: 'Number', 30: 'Number'}

>>>

4. The get method

The get() method returns the value for the specified key if key is in dictionary. This
method takes two parameters key and value. The get method can return either key,
or value or nothing.

Syntax

[Link](keys, value])

For example

>>> student={'name':'AAA','roll': 10,'marks':98} #creation of dictionary

>>> print("Name: ",[Link]('name'))

Name: AAA

>>> print("roll: ",[Link]('roll'))

roll: 10

>>> print("marks: ",[Link]('marks'))

marks: 98
>>> print("Address: ", [Link]('address')) #this key is 'address' is not
specified in the list

Address: None #Hence it returns none

>>>

5. The value method

This method returns the value object that returns view object that displays the list
of values present in the dictionary.

For example :

>>> my_dictionary ={'marks 1:99,'marks2:96,'marks3:97}#creating dictionary

>>> print(my_dictionary.values()) #displaying values

dict_values([99, 96, 97])

>>>

6. The pop method

This method The pop() method removes and returns an element from a dictionary
having the given key.

Syntax

pop(keys, default])

where key is the key which is searched for removing the value. And default is the
value which is to be returned when the key is not in the dictionary. For example

my_dictionary={1:'Red', 2:'Blue', 3:'Green'}#creation of dictionary

>>> val = my_dictionary.pop(1) #removing the element with key 1

>>> print("The popped element is: ",val)

The popped element is: Red

>>> val=my_dictionary.pop(5,3)
#specifying default value. When the specified key is not present in the list,
then the

#default value is returned.

>>>print("The popped element using default value is: ",val)

The popped element using default value is: 3 #default value is returned

>>>

Example 4.3.1 Define dictionary in Python. Do the following operations on


dictionaries

i) Initialize two dictionaries with key and value pair.

ii) Compare the two dictionaries with master key list and print missing keys

iii) Find keys that are in first and not in second dictionary

iv) Find same keys in two dictionaries

v) Merge two dictionaries and create a new dictionary using a single expression.

Solution : Dictionary -

i) Initialize two dictionaries with key and value pair.

d1 = {1:"AAA",2:"BBB",3:"CCC"}

print("Dictionary#1")

print(d1)

print("Dictionary#2")

d2 = {10:"Pune",20:"Mumbai",30:"Chennai"}

print(d2)
ii) Compare the two dictionaries with master key list and print missing keys

First_Dict = {"Color": ["Red", "Blue", "Green", "Yellow"],


"Fruit": ["Mango", "Banana", "Apple"],
"Flower": ["Rose", "Jasmine", "Lotus", "Lily"],
"Country": ["India", "Japan"]}
Second_Dict = {"Color": ["Red", "Blue", "Green", "Yellow"],
"Fruit": ["Mango", "Banana", "Apple"],
"Flower": ["Rose", "Tulip", "Daffodil"],
"City":["Pune", "Chennai"]}
key_lst=[ ]
values_lst=[ ]
for key, value in First_Dict.items() and Second_Dict.items():
if key in First_Dict.keys() and Second_Dict.keys():
if key in Second_Dict.keys() and First_Dict.keys() :
continue
else:
key_lst.append(key)
else:
key_lst.append(key)
if value in First_Dict.values() and Second_Dict.values():
if value in Second_Dict.values() and First_Dict.values() :
continue
else:
values_lst.append(value)
else:
values_lst.append(value)
for key, value in Second_Dict.items() and First_Dict.items():
if key in First_Dict.keys() and Second_Dict.keys():
if key in Second_Dict.keys() and First_Dict.keys() :
continue
else:
key_lst.append(key)
else:
key_lst.append(key)
if value in First_Dict.values() and Second_Dict.values():
if value in Second_Dict.values() and First_Dict.values():
continue
else:
values_lst.append(value)
else:
values_lst.append(value)
print("Missing Keys: ",key_lst[0],": Missing Values", values_lst[0])
print("Missing Keys: ",key_lst[1],": Missing Values", values_lst[1])

Output

Missing Keys: City : Missing Values (Pune', 'Chennai']

Missing Keys: Country : Missing Values ['India', 'Japan']

iii) Find keys that are in first and not in second dictionary

d1 = {"Color":"Red", "Fruit":"Mango", "Flower":"Rose", "Country":"India"}

d2 = {"Color": "Red", "Fruit": "Mango","City":"Pune"}

print([Link]()-[Link]())

Output:

{'Flower', 'Country'}

iv) Find same keys in two dictionaries

d1 = {"Color": "Red", "Fruit":"Mango", "Flower":"Rose", "Country":"India"}

d2 = {"Color": "Red", "Fruit":"Mango", "City":"Pune"}

d3 = [ ]

for item in [Link]():

if item in [Link]():

[Link](item)

print(d3)

Output

['Color', 'Fruit']

>>>
v) Merge two dictionaries and create a new dictionary using a single expression.

dict1 = {1: "AAA", 2:"BBB"}

dict2 = {3: "CCC", 4:"DDD"}

result = (key:value for d in (dict1, dict2] for key,value in [Link]()}

print(result)

Output

{1: 'AAA', 2: 'BBB', 3: 'CCC", 4: 'DDD'}

>>>

Review Questions

1. What is a dictionary in Python ? Give example.

AU: Jan.-18, Marks 4

2. Appraise the operations for dynamically manipulating dictionaries.

AU: Jan.-18, Marks 12


Advanced List Processing - List Comprehension
• Python supports a concept called "list comprehensions". It can be used to
construct lists in a very natural, easy way, like a mathematician is used to do.

• In Python, we can write the expression almost exactly like mathematics with
special cryptic syntax.

• For example:

>>> L = [x**2 for x in range(10)]

>>>L

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>>

• The above code creates a list of square numbers from 0 to 10. This list can be
created using a simplified expression “x**2 for x in range(10)". This is basically
list comprehension.

• List comprehensions apply an arbitrary expression to items in an iteration.

• The list comprehension is achieved using the tools like map, lambda and filter.

1. Map

• The map() function applies the values to every member of the list and returns the
result.

• The map function takes two arguments -

result = map(function, sequence)

For example

>>> def increment_by_three(x):

return x+3

>>> new_list=list(map(increment_by_three,range(10)))

>>> new_list
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

>>>

Another Example:

There is a built in function for calculating length of the string and i.e. len( ). We
can pass this function to map and find the length of every element present in the
list as a list.

>>> names=['Sandip', 'Lucky','Mahesh','Sachin']

>>> lengths=list(map(len, names))

>>> lengths

[6, 5, 6, 6]

>>>

2. Filter

• The Filter( ) function selects some of the elements and filters out others. If we use

• if with list compression, it is almost equivalent to the filter built-in.

• This function takes two arguments -

result = filter(function, sequence)

• For example –

>>> def even_fun(x):

return x%2= = 0

>>> r = filter(even_fun,(1,2,3,4,5))

>>> list(r) [2, 4]

>>>

• In above example, using filter( ) function the odd numbers are filtered out and
only even numbers are displayed.
• filter( ) works in the similar manner like map( ), it applies function to all the
elements of the list.

3. Lambda

• The lambda function is a simple inline function that is used to evaluate the
expression using the given list of arguments.

• The syntax is

lambda argument_list : expression

where the argument_list consists of a comma separated list of arguments and the
expression is an arithmetic expression using these arguments.

• For example:

>>> sum = lambda x,y:x+y

>>> sum(1,3)

>>>

Thus the expression x+y is evaluated and the result of evaluation is returned.

4. Reduce

• The kind of function that combines sequence of elements into a single value is
called reduce function.

• The reduce function also takes two arguments -

Result = reduce(function, sequence)

• The function reduce() had been dropped from the core of Python when migrating
to Python 3. Hence for using the reduce function we have to import functools to be
capable of using reduce.

• For example

>>> import functools

>>> [Link](lambda x,y:x+y,[1,2,3,4])


10

>>>

Example 4.4.1 Following is a list of items purchased

Write a python program, which returns a list with 2 tuples - Each tuple consists of
item no, and product of price and quantity.

If value of the order is less than 100 then the product is increased by 10. Write a
program in Python using map and lambda functions

Solution :

>>> order=[["111", 12,20],["112",5,100],["113",7,5]]

>>> min_order=100

>>> Total_Bill=list(map(lambda x:x if x[1]>=min_order else(x[0],x[1]+10),

map(lambda x:(x[0],x[1]*x[2]),order)))

>>> print(Total_Bill)

[('111', 240), ('112', 500), ('113', 45)]

>>>

Example 4.4.2 Write a Python program to display power of 2 using Anonymous


function.

Solution :

The Anonymous function is a lambda function. We can write the program to


display the power of 2 using Anonymous function
[Link]

Review Question

1. What is list comprehension in Python? Explain with example.

You might also like