Python Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

R20 Python Unit-3

V.K.R, V.N.B & A.G.K COLLEGE OF ENGINEERING::GUDIVADA


(Approved by AICTE, New Delhi & Affiliated to JNTUK, Kakinada)
An ISO 9001:2015 Certified Institute
Gudivada , Krishna District, Andhra Pradesh - 521301

UNIT III

LISTS AND DICTIONARIES:

LISTS:
 List is used to store the group of values & we can manipulate them, in list thevalues
are storesin index format starts with 0.
 List is mutable object so we can do the manipulations.
 A python list is enclosed between square ([]) brackets.
 In list insertion order is preserved it means in which order we inserted elementsame
orderoutput is printed.
 A list can be composed by storing a sequence of different type of values separatedby
commas.
 The list contains forward indexing & backward indexing.

Syntax: <list_name> = [value1,value2,value3,...,valuen]


Example:
data1=[1,2,3,4] # list of integers
data2=['x','y','z'] # list of String
data3=[12.5,11.6] # list of floats
data4=[] # empty list
data5=['TEC',10,56.4,'a'] # list with mixed data types

Accessing List data:


 The list items are accessed by referring to the index number.
 Negative indexing means beginning from the end, -1 refers to the last item, -2 refers
to thesecond last item etc.
 A range of indexes can be specified by specifying where to start and where to end the
range.When specifying a range, the return value will be a new list with the specified
items.
 Note: The search will start at index 2 (included) and end at index 5 (not included).
 By leaving out the start value, the range will start at the first item.
 By leaving out the end value, the range will go on to the end of the list:

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Examples:
1. x=["apple", "banana", "cherry"]print(x[1])
Output: banana
2. x= ["apple", "banana", "cherry"]
print(x[-1])
Output: cherry
3. x= ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(x[2:5])
Output: ['cherry', 'orange', 'kiwi']
4. x = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(x[:4])
Output: ['apple', 'banana', 'cherry', 'orange']
5. x= ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(x[2:])
Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

Creating lists using range() function:


We can use range() function to generate a sequence of integers which can be stored in a list. To store
numbers from 0 to 10 in a list as follows.
numbers = list( range(0,11) )
print(numbers) # [0,1,2,3,4,5,6,7,8,9,10]
To store even numbers from 0 to 10in a list as follows.
numbers = list( range(0,11,2) ) print(numbers) # [0,2,4,6,8,10]
Looping on lists:
We can also display list by using for loop (or) while loop. The len( ) function useful to know the
numbers of elements in the list. while loop retrieves starting from 0th to the last element i.e. n-1 Ex-1:
numbers = [1,2,3,4,5]for i in
numbers:
print(i,end="")
Output:
12345
Updating and deleting lists:
Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the
elements of a list depending upon our requirements.
Appending an element means adding an element at the end of the list. To, append a new element tothe list,
we should use the append() method.
Example:
lst=[1,2,4,5,8,6]
print(lst) # [1,2,4,5,8,6]
lst.append(9)
print(lst) # [1,2,4,5,8,6,9]
Updating an element means changing the value of the element in the list. This can be done by
accessing the specific element using indexing or slicing and assigning a new value.
Example:
lst=[4,7,6,8,9,3]
print(lst) # [4,7,6,8,9,3]
lst[2]=5 # updates 2nd element in the list
print(lst) # [4,7,5,8,9,3]
lst[2:5]=10,11,12 # update 2nd element to 4th element in the list

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
print(lst) # [4,7,10,11,12,3]
Deleting an element from the list can be done using ‘del’ statement. The del statement takes the
position number of the element to be deleted.

Example:
lst=[5,7,1,8,9,6]
del lst[3] # delete 3rd element from the list i.e., 8
print(lst) # [5,7,1,9,6]
If we want to delete entire list, we can give statement like del lst.
Concatenation of Two lists:
We can simply use „+‟ operator on two lists to join them. For example, „x‟ and „y‟ are two lists. Ifwe wrte
x+y, the list „y‟ is joined at the end of the list „x‟.
Example:
x=[10,20,32,15,16]
y=[45,18,78,14,86]
print(x+y) # [10,20,32,15,16,45,18,78,14,86]
Repetition of Lists:
We can repeat the elements of a list „n‟ number of times using „*‟ operator.
x=[10,54,87,96,45]
print(x*2) # [10,54,87,96,45,10,54,87,96,45]

Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not in‟ operator. If the element is a
member of the list, then „in‟ operator returns True otherwise returns False. If the element is not in the list,
then „not in‟ operator returns True otherwise returns False.
Example:
x=[10,20,30,45,55,65]a=20
print(a in x) # Truea=25
print(a in x) # Falsea=45
print(a not in x) # Falsea=40
print(a not in x) # True

Methods in Lists:
1. A.index(X): Returns the first occurrence of X in the list A.
PROGRAM Output

A=[1,3,13,45,56,62,45,58,89,13,3,56,1] 3
print(A.index(45))

2. A.append(X): Adds the element X at the end of list A.

Program Output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 3, 13, 45, 56, 62, 45, 58, 89, 13, 3, 56, 1, 97]
A.append(97)
print(A)

3. insert( i,X ): Inserts X to the list A in ith position.

Program Output

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 3, 13, 45, 'CSE', 56, 62, 45, 58, 89, 13,
A.insert(4,"CSE") 3, 56, 1]
print(A)

4. B=A.copy(): copies all the list elements of A into B.


Program Output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] B= [1, 3, 13, 45, 56, 62, 45, 58, 89, 13, 3, 56, 1]
B=A.copy()
print("B=", B)
5. A.extend(B): Appends list B to list A.
program output
A=[1,3,13,45,56,] A= [1, 3, 13, 45, 56, 62, 45, 58, 89, 13, 3, 56, 1]
B=[62,45,58,89,13,3,56,1] B= [62, 45, 58, 89, 13, 3, 56, 1]
A.extend(B)
print("A=",A)
print("B=",B)
6. A.count(X): Returns number of occurrences of X in the list A.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] 2
print(A.count(45))
7. A.remove(X): Removes X from the list X.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 3, 45, 56, 62, 45, 58, 89, 13, 3, 56, 1]
A.remove(13)
print(A)
8. A.pop(): Removes the ending element from list A.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 3, 13, 45, 56, 62, 45, 58, 89, 13, 3, 56]
A.pop()
print(A)
9. A.sort(): Sorts the elements of list A into ascending order.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 1, 3, 3, 13, 13, 45, 45, 56, 56, 58, 62, 89]
A.sort()
print(A)
10. A.reverse(): Reverses the sequence of elements in the list.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] [1, 56, 3, 13, 89, 58, 45, 62, 56, 45, 13, 3, 1]
A.reverse()
print(A)
11. A.clear(): Removes all elements from the list A.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] []
A.clear()
print(A)
12. max(A): Returns biggest element in the list A.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] 89
print(max(A))
13. min(A): Returns smallest element in the list B.
program output
A=[1,3,13,45,56,62,45,58,89,13,3,56,1] 1
print(min(A))
14. len(A): Returns the length of list A

program output
A=[1,2,3,4,5] 5
print(len(A))

Nested Lists:
A list within another list is called a nested list. We know that a list contains several elements. When we
take a list as an element in another list, then that list is called a nested list.
program output
a=[[1,2,3],[4,5,6],[7,8,9]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a) [4, 5, 6]
print(a[1]) 5
print(a[1][1]) [7, 8, 9]
print(a[2])

Range of Negative Indexes: Specify negative indexes if you want to start thesearch from
theend of the list.
Example: x = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(x[-4:-1])
Output: ['orange', 'kiwi', 'melon']
Check if Item Exists: To determine if a specified item is present in a list use the inkeyword.
Example: Check if "apple" is present in the list:
fruits= ["apple", "banana", "cherry"]if
"apple" in fruits:
print("Yes, 'apple' is in the fruits list")
Output: Yes, 'apple' is in the fruits list
Change Item Value:
To change the value of a specific item, refer to the index number.

Example: Change the second item:


x = ["apple", "banana", "cherry"]x[1]
= "blackcurrant"
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
print(x)
Output: ['apple', 'blackcurrant', 'cherry']
• To insert more than one item, create a list with the new values, and specify theindex
numberwhere you want the new values to be inserted.

Example: Change the second value by replacing it with two new values:
x = ["apple", "banana", "cherry"]
x[1] = ["blackcurrant", "watermelon"]
print(x)
Output: ['apple', ['blackcurrant', 'watermelon'], 'cherry']
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and
referto the range of index numbers where you want to insert the new values.
Example: Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
x = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
x[1:3] = ["blackcurrant", "watermelon"]
print(x)
Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Loop Through a List:
We can loop through the list items by using a for loop.Print
all items in the list, one by one.
Use the range() and len() functions to print all items by referring to their index number:

Example – 1:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Output:
apple banana
cherry
Using a While Loop: Use the len() function to determine the length of the list, then start at
0and loop your way through the list items by refering to their indexes. Remember to
increase theindex by 1 after each iteration.
Example – 1:
thislist = ["apple", "banana", "cherry"]i = 0
while i < len(thislist):
print(thislist[i]) i = i
+ 1 Output:
apple
banana
cherry

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Looping Using List Comprehensive: It offers the shortest syntax for looping throughlists.
Example – 1:
thislist = ["apple", "banana", "cherry"][print
x for x in thislist]
Output:
apple banana
cherry
Sort Lists: Sort List Alphanumerically. List objects have a sort() method that will sortthe
list alphanumerically, ascending, by default.To sort descending, use the keyword argument
reverse = True.
Example -1:
List1= ["orange", "mango", "kiwi", "pineapple", "banana"]
List1.sort()
print(List1)
Output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Customize Sort Function: we can also customize you own function by using the
keywordargument key = function. The function will return a number that will be used tosort
the list (thelowest number first):
Example -1: Sort the list based on how close the number is to 50:
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc) print(thislist)
Output:
[50, 65, 23, 82, 100]
Note: By default the sort() method is case sensitive, resulting in all capital letters being
sorted after lower case letters:
Example – 1:
List1 = ["banana", "Orange", "Kiwi", "cherry"]
List1.sort()
print(List1)
Output: ['Kiwi', 'Orange', 'banana', 'cherry']
Case Insensitive Sort: we can use built-in functions as key functions when sorting a list.So if
you want a case-insensitive sort function, use str.lower as a key function.
Example – 1:
List1 = ["banana", "Orange", "Kiwi", "cherry"]
List1.sort(key = str.lower)
print(List1)
Output: ['banana', 'cherry', 'Kiwi', 'Orange']

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries arewritten
with curly brackets, and they have keys and values.
Each key is separated from its value by a colon (:), the items are separated by commas, and the wholething
is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces,
like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Creating a Dictionary
A Dictionary can be created by placing sequence of elements within curly {} braces, separated by‘comma’.
Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its
key:value. Values in a dictionary can be of any data type and can be duplicated,whereas keys can’t be
repeated and must be immutable.
Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Example:
# Creating a Dictionary# with
Integer Keys
Dict = {1: 'Pragati', 2: 'Engineering', 3: 'College'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary# with
Mixed keys
Dict = {'Name': 'PEC', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Pragati', 2: 'Engineering', 3: 'College'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'PEC'}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be createdby
just placing to curly braces{}.
Example:
# Creating an empty DictionaryDict =
{}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary# with
dict() method
Dict = dict({1: 'Pragati', 2: 'Engineering', 3:'College'})
print("\nDictionary with the use of dict(): ") print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Pragati'), (2, 'College')])
print("\nDictionary with each item as a pair: ")
print(Dict)

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3

Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}

Accessing Values
To access dictionary elements, you can use the familiar square brackets along with the key to obtainits
value.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}print
("Name:", dict['Name'])
print ("Age:", dict['Age'])
Output:
Name: ZaraAge:
7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}print
("Name:", dict['Alice'])
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module> print
("Name:", dict['Alice'])
KeyError: 'Alice'
There is also a method called get() that will also help in accessing the element from a dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict.get('Class'))
Output:
First

Adding and modifying an item in a Dictionary


In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in
a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an
existing Dictionary.
Example:
# Creating an empty Dictionarydict =
{}
print("Empty Dictionary: ")
print(dict)
# Adding elements one at a timedict[0]
= 'Pragati'
dict[2] = 'Engineering'dict[3]
= 'College'
print("\nDictionary after adding 3 elements: ")
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
print(dict)
# Adding set of values # to a
single Key
dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")

print(dict)
# Updating existing Key's Valuedict[2]
= 'Welcome' print("\nUpdated key
value: ") print(dict)
# Adding Nested Key value to Dictionary dict[5]
= {'Nested' :{'1' : 'Good', '2' : 'Day'}}
print("\nAdding a Nested Key: ")
print(dict)

Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Pragati', 2: 'Engineering', 3: 'College'}

Dictionary after adding 3 elements:


{0: 'Pragati', 2: 'Engineering', 3: 'College', 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'Pragati', 2: 'Welcome', 3: 'College', 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Pragati', 2: 'Welcome', 3: 'College', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Good', '2': 'Day'}}}
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry dict['School'] =
"DPS School"; # Add new entryprint ("Age:",
dict['Age'])
print ("School:", dict['School']) print
("The dictionary is:") print (dict)
Output:
Age: 8
School: DPS SchoolThe
dictionary is:
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Deleting Items
del keyword can be used to in place delete the key that is present in the dictionary. One drawback that
can be thought of using this is that is raises an exception if the key is not found and hence non-existence
of key has to be handled.
Example:
# Python code to demonstrate#
removal of dict. pair
# using del
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}#
Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using del to remove a dict#
removes Mani
del test_dict['Mani']
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(test_dict))#
Using del to remove a dict
# raises exception
del test_dict['Manjeet']
Ouput:
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}The
dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
Exception :
Traceback (most recent call last):
File "/home/44db951e7011423359af4861d475458a.py", line 20, indel
test_dict['Manjeet']
KeyError: 'Manjeet'
pop() can be used to delete a key and its value inplace. Advantage over using del is that it provides
the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also
returns the value of key that is being removed in addition to performing a simpledelete operation.
Example:
# Python code to demonstrate#
removal of dict. pair
# using pop()
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
# Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using pop() to remove a dict. pair #
removes Mani
removed_value = test_dict.pop('Mani')
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(test_dict)) print
("The removed key's value is : " + str(removed_value)) print ('\r')
# Using pop() to remove a dict. pair #
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
doesn't raise exception
# assigns 'No Key found' to removed_value
removed_value = test_dict.pop('Manjeet', 'No Key found')

# Printing dictionary after removal


print ("The dictionary after remove is : " + str(test_dict))
print ("The removed key's value is : " + str(removed_value))
Output:
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21}The
dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : 21
The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : No Key found

Nested Dictionaries
A nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single
dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two
dictionary each having own key and value.
Creating a Nested Dictionary:
Example:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
In the above program, people is a nested dictionary. The internal dictionary 1 and 2 is assigned to people.
Here, both the dictionary have key name, age , sex with different values. Now, we print theresult of people.
Accessing elements of a Nested Dictionary:
To access element of a nested dictionary, we use indexing [] syntax in Python.
Example:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
Output:
John27
Male
Adding element to a Nested Dictionary
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
Output:
{'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}
In the above program, we create an empty dictionary 3 inside the dictionary people. Then, we add the
key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex
and married one by one. When we print the people[3], we get key:value pairs of dictionary

Adding another dictionary to the nested dictionary:


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}
print(people[4])
Output:
{'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}
In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex
with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested
dictionary people.
Deleting elements from a Nested Dictionary:
In Python, we use “ del “ statement to delete elements from nested dictionary.
Example:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}del
people[3]['married']
del people[4]['married']
print(people[3])
print(people[4]) Output:
{'name': 'Luna', 'age': '24', 'sex': 'Female'}
{'name': 'Peter', 'age': '29', 'sex': 'Male'}
In the above program, we delete the key:value pairs of married from internal dictionary 3 and 4. Then,
we print the people[3] and people[4] to confirm changes.
How to delete dictionary from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}del
people[3], people[4]
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
In the above program, we delete both the internal dictionary 3 and 4 using del from the nested
dictionary people. Then, we print the nested dictionary people to confirm changes.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
3.2.7. Difference between a List and a Dictionary
PROGRAM OUTPUT
List is a collection of index values pairs as that Dictionary is a hashed structure of key and
of array in C++. value pairs.

List is created by placing elements in [ ] Dictionary is created by placing elements in { }


separated by commas “, “ as “key”:”value”, each key value pair is
separated by commas “, ”

The indices of list are integers starting from 0. The keys of dictionary can be of any data type.

The elements are accessed via indices. The elements are accessed via key-values.

The order of the elements entered is maintained. There is no guarantee for maintaining order.

Dictionary Methods:
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
1. Dictionary clear():
The clear() method removes all the elements from a dictionary.

Syntax: dictionary.clear()
Example: Remove all elements from the car list. car =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
Output: {}
2. Dictionary copy():
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only beareference to
dict1, and changes made in dict1 will automatically also be made in dict2.
The copy() method returns a copy of the specified dictionary.
Syntax: dictionary.copy() Example:
Copy the car dictionary.car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Another way to make a copy is to use the built-in function dict().


Example: Make a copy of a dictionary with the dict() function. thisdict
={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3. Dictionary fromkeys():
• •The fromkeys() method returns a dictionary with the specified keys and the
specified value.
Syntax: dict.fromkeys(keys, value)Here,
keys Required. An iterable specifying the keys of the new dictionary value
Optional. The value for all keys. Default value is None Example: 1 Create
a dictionary with 3 keys, all with the value 0.
x = ('key1', 'key2', 'key3')y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Output: ['key1': 0, 'key2': 0, 'key3': 0]
4. Dictionary get():
The get() method returns the value of the item with the specified key.
Syntax: dictionary.get(keyname, value)Here,
keyname Required. The keyname of the item you want to return the value from
value Optional. A value to return if the specified key does not exist. Default value None.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Example-1: Get the value of the "model" item.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)
Output: Mustang
5. Dictionary items():
The items() method returns a view object. The view object contains the key-value pairs of
thedictionary, as tuples in a list.

The view object will reflect any changes done to the dictionary.
Syntax: dictionary.items()
Example-1: Return the dictionary's key-value pairs:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
6. Dictionary keys():
The keys() method returns a view object. The view object contains the keys of the
dictionary, asa list.
The view object will reflect any changes done to the dictionary.
Syntax: dictionary.keys() Example
– 1: Return the keys.car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Output: dict_keys(['brand', 'model', 'year'])

7. Dictionary pop():
The pop() method removes the specified item from the dictionary.
The value of the removed item is the return value of the pop() method.
Syntax: dictionary.pop(keyname, defaultvalue) Here,
keyname Required. The keyname of the item you want to remove
defaultvalue Optional. A value to return if the specified key do not exist. If this parameteris not
specified, and the no item with the specified key is found, an error is raised.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
Example: 1 Remove "model" from the dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model") print(car)
Output: {'brand': 'Ford', 'year': 1964}
8. Dictionary popitem():
The popitem() method removes the item that was last inserted into the dictionary. In
versionsbefore 3.7, the popitem() method removes a random item.

The removed item is the return value of the popitem() method, as a tuple.
Syntax: dictionary.popitem()
Example: 1 Remove the last item from the dictionary. car =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
Output: {'brand': 'Ford', 'model': 'Mustang'}
9. Dictionary setdefault():
The setdefault() method returns the value of the item with the specified key. If the
key does not exist, insert the key, with the specified value.
Syntax: dictionary.setdefault(keyname, value) Here,
keyname Required. The keyname of the item you want to return the value from
value Optional. If the key exist, this parameter has no effect. If the
key does not exist, this value becomes the key's value Default
value None.
Example: 1 Get the value of the "model" item.car =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Output: Mustang

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
10. Dictionary update():
The update() method inserts the specified items to the dictionary.
The specified items can be a dictionary, or an iterable object with key value pairs.
Syntax: dictionary.update(iterable)Here,
iterable A dictionary or an iterable object with key value pairs, that will be inserted to thedictionary.
Example: Insert an item to the dictionary. car =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
11. Dictionary values():
• •The values() method returns a view object. The view object contains the values of
thedictionary, as a list.

The view object will reflect any changes done to the dictionary, see example below.
Syntax: dictionary.values()
Example: 1 Return the values.car =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
Output: dict_values(['Ford', 'Mustang', 1964])
12.del
The del keyword removes the item with the specified key name.
Example: 1 thisdict =
{ "brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Output: {'brand': 'Ford', 'year': 1964}

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Python Functions
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our
program growslarger and larger, functions make it more organized and
manageable.
It avoids repetition and makes the code reusable.

Syntax of Function:
def function_name(parameters):
"""docstring"""
statement(s)
return
Above shown is a function definition that consists of the following components.

o Keyword def that marks the start of the function header.


o A function name to uniquely identify the function. Function naming follows thesame
rules ofwriting identifiers in Python.
o Parameters (arguments) through which we pass values to a function. They are
optional.
o A colon (:) to mark the end of the function header.
o documentation string (docstring) to describe what the function does which is
optional.
o One or more valid python statements that make up the function body. Statements must
have thesame indentation level (usually 4 spaces).
o return statement to return a value from the function which is optional.
Example of a function:
def greet(name):
"""
This function greets tothe
person passed in as
a parameter """
print("Hello, " + name + ". Good morning!")

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Returning multiple values from a function:
A function can returns a single value in the programming languages like C, C++ and JAVA. But, in
python, a function can return multiple values. When a function calculates multiple results and wants to
return the results, we can use return statement as:
return a, b, c
Here, three values which are in „a‟, „b‟ and „c‟ are returned. These values are returned by the function as
a tuple. To grab these values, we can three variables at the time of calling the functionas:
x, y, z = functionName( )
Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.
Example:
def calc(a,b):
c=a+b d=a-b
e=a*b
return c,d,e x,y,z=calc(5,8)
print("Addition=",x)
print("Subtraction=",y)
print("Multiplication=",z)

Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and any modifications to
that value will not reflect outside the function. In python, the values are sent to functions by means of
object references. We know everything is considered as an object in python.All numbers, strings, tuples,
lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a memory block where we can store some
value. In this case, an object with the value „10‟ is created in memory for which a name „x‟ is attached.
So, 10 is the object and „x‟ is the name or tag given to that object. Also, objects are created on heap
memory which is a very huge memory that depends on the RAM of our computer system.

Example: A Python program to pass an integer to a function and modify it.


def modify(x):
x=15
print("inside",x)x=10
print("outside",x)
modify(x)
print("outside",x)
Output:
outside 10
inside 15
outside 10
From the output, we can understand that the value of „x‟ in the function is 15 and that is not
available outside the function. When we call the modify( ) function and pass „x‟ as: modify(x)
We should remember that we are passing the object references to the modify( ) function. The object is 10
and its references name is „x‟. This is being passed to the modify( ) function. Inside the function, we are
using:
x=15
This means another object 15 is created in memory and that object is referenced by the name „x‟. The
reason why another object is created in the memory is that the integer objects are immutable (not
modifiable). So in the function, when we display „x‟ value, it will display 15. Once we come outside the

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
function and display „x‟ value, it will display numbers of „x‟ inside and outside the function, and we see
different numbers since they are different objects.
In python, integers, floats, strings and tuples are immutable. That means their data cannot be modified.
When we try to change their value, a new object is created with the modified value.
Pass by Reference:
Pass by reference represents sending the reference or memory address of the variable to the function.The
variable value is modified by the function through memory address and hence the modified value will
reflect outside the function also.
In python, lists and dictionaries are mutable. That means, when we change their data, the same object gets
modified and new object is not created. In the below program, we are passing a list of numbers to modify (
) function. When we append a new element to the list, the same list is modified and hencethe modified list
is available outside the function also.
Example: A Python program to pass a list to a function and modify it.
def modify(a):
a.append(5) print("inside",a)
a=[1,2,3,4]
print("outside",a)modify(a)
print("outside",a)Output:
outside [1, 2, 3, 4, 5]
inside [1, 2, 3, 4, 5]
outside [1, 2, 3, 4, 5]

Formal and Actual Arguments:


When a function is defined, it may have some parameters. These parameters are useful to receive values
from outside of the function. They are called „formal arguments‟. When we call the function,we should
pass data or values to the function. These values are called „actual arguments‟. In the following code, „a‟
and „b‟ are formal arguments and „x‟ and „y‟ are actual arguments.

Example:
def add(a,b): # a, b are formal arguments
c=a+b print(c)
x,y=10,15
add(x,y) # x, y are actual arguments
The actual arguments used in a function call are of 4 types:
a) Positional arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments
a) Positional Arguments:
These are the arguments passed to a function in correct positional order. Here, the number of arguments
and their position in the function definition should match exactly with the number and position of
argument in the function call.
def attach(s1,s2):
s3=s1+s2 print(s3)
attach("New","Delhi") #Positional arguments
This function expects two strings that too in that order only. Let‟s assume that this function attaches the
two strings as s1+s2. So, while calling this function, we are supposed to pass only two strings as:
attach("New","Delhi")
The preceding statements displays the following output NewDelhiSuppose, we passed "Delhi" first and then "New",
then the result will be: "DelhiNew". Also, if we tryto pass more than or less than 2 strings, there will be an error.
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. For example, thedefinition
of a function that displays grocery item and its price can be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which value is for
what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another keyword „price‟ and its value.
Please observe these keywords are nothing but the parameter names which receive these values. We can
change the order of the arguments as:
grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not be any problem as theparameter
names will guide where to store that value.
def grocery(item,price):
print("item=",item)
print("price=",price)
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments Output:
item= sugar price=
50.75item= oil
price= 88.0
c) Default Arguments:
We can mention some default value for the function parameters in the definition. Let‟s take thedefinition of
grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second argument
is „price‟ and its default value is mentioned to be 40.00. at the time of calling this function, if we do not
pass „price‟ value, then the default value of 40.00 is taken. If we mention the „price‟ value, then that
mentioned value is utilized.

So, a default argument is an argument that assumes a default value if a value is not provided in the function
call for that argument.
Example: def grocery(item,price=40.00):
print("item=",item) print("price=",price)
grocery(item="sugar",price=50.75)
grocery(item="oil")
Output:
item= sugar price=
50.75
item= oil
price= 40.0
d) Variable Length Arguments:
Sometimes, the programmer does not know how many values a function may receive. In that case,the
programmer cannot decide how many arguments to be given in the function definition. for example, if the
programmer is writing a function to add two numbers, he/she can write:
add(a,b)
But, the user who is using this function may want to use this function to find sum of three numbers. In that
case, there is a chance that the user may provide 3 arguments to this function as:
add(10,15,20)
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
Then the add( ) function will fail and error will be displayed. If the programmer want to develop a function
that can accept „n‟ arguments, that is also possible in python. For this purpose, a variable length argument
is used in the function definition. a variable length argument is an argument that canaccept any number of
values. The variable length argument is written with a „*‟ symbol before it in the function definition as:
def add(farg, *args):
here, „farg‟ is the formal; argument and „*args‟ represents variable length argument. We can pass 1 or
more values to this „*args‟ and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print("sum is",sum+farg)add(5,10)
add(5,10,20)
add(5,10,20,30)
Output:
sum is 15
sum is 35
sum is 65

Optional keyword arguments:


file: a file-like object (stream); defaults to the current sys.stdout.sep:
string inserted between values, default a space.
end: string appended after the last value, default a newline.flush:
whether to forcibly flush the stream.
Docstrings for Python Modules:
o The docstrings for Python Modules should list all the available classes, functions,
objects andexceptions that are imported when the module is imported.
o They should also have a one-line summary for each item.
o They are written at the beginning of the Python file.

Example 4: docstrings for the builtin module in Python called pickle.


import pickle
print(pickle. doc__)
Docstrings for Python Classes:

 The docstrings for classes should summarize its behavior and list the public
methods andinstance variables.
 The subclasses, constructors, and methods should each have their own docstrings.
Example 5: Docstrings for Python class.
 class Person:
"""
A class to represent a person.
...
Attributes

name : str
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
first name of the personage :
int
age of the person
"""
Methods

info(additional=""):
Prints the person's name and age.
"""
def info(self, additional=""): """
Prints the person's name and age.
If the argument 'additional' is passed, then it is appended after the main info.
Output:
>>> print(Person. doc )
Types of Functions:
Basically, we can divide functions into the following two types:
1. Built-in functions - Python has several functions that are readily available for use.
These functionsare called built-in functions.
Examples:
abs(),any(),all(),ascii(),bin(),bool(),callable(),chr(),compile(),classmethod(),delattr(),dir(),
divmod(),staticmethod(),filter(),getattr(),globals(),exec(),hasattr(),hash(),isinstance(),issu
bclass(),iter(),locals(), map(), next(),memoryview(),object(),property(),repr(),reversed(),vars(),
import (),super() Note: Refer this link https://www.programiz.com/python-
programming/methods/built- in/abs for detailed explanation of each function.
2. User-defined functions -
• Functions that we define ourselves to do certain specific task are referred as user-
definedfunctions.
• If we use functions written by others in the form of library, it can be termed as library
functions.
• All the other functions that we write on our own fall under user-defined functions. So, our
user-defined function could be a library function to someone else.
Advantages of user-defined functions:
• User-defined functions help to decompose a large program into small segments which
makesprogram easy to understand, maintain and debug.
• If repeated code occurs in a program. Function can be used to include those codes and
executewhen needed by calling that function.
• Programmars working on large project can divide the workload by making different
functions.
Example:
def add_numbers(x,y):
sum = x + y
return sum num1
=5
num2 = 6
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
print("The sum is", add_numbers(num1, num2))
Output:
The sum is 11
Recursive Function:
• A function that calls itself is known as Recursive Function.
• A physical world example would be to place two parallel mirrors facing each other. Any object
inbetween them would be reflected recursively.
• The following image shows the working of a recursive function called recurse.

Example:
• •Factorial of a number is the product of all the integers from 1 to that number.
• •the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

def factorial(x):
if x == 1:
return 1else:
return (x * factorial(x-1))num =
3
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 3 is 6
This recursive call can be explained in the following steps. factorial(3)
# 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1 3 * 2 #
return from 2nd call
6 # return from 1st call
Advantages of Recursion:
1.Recursive functions make the code look clean and elegant.
2.A complex task can be broken down into simpler sub-problems using recursion.
3.Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion:

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3.Recursive functions are hard to debug.
Python Anonymous/Lambda Function:
• In Python, an anonymous function is a function that is defined without a name.
• While normal functions are defined using the def keyword in Python, anonymous functions are
definedusing the lambda keyword.
• Hence, anonymous functions are also called lambda functions.
• Lambda functions can have any number of arguments but only one expression. The expression
isevaluated and returned. Lambda functions can be used wherever function objects are required.

Syntax of Lambda Function: lambda arguments: expression


Example:
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
Output:
10

Use of Lambda Function in python:


• We use lambda functions when we require a nameless function for a short period of time.
• In Python, we generally use it as an argument to a higher-order function (a function that takes in
otherfunctions as arguments). Lambda functions are used along with built-in functions like filter(), map()
etc.

Example use with filter(): The filter() function in Python takes in a function and a list as arguments.#
Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output:
[4, 6, 8, 12]
Example use with map(): The map() function in Python takes in a function and a list.#
Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Output: [2, 10, 8, 12, 16, 22, 6, 24]

Scope and Lifetime of variables:


• Scope of a variable is the portion of a program where the variable is recognized. Parameters
andvariables defined inside a function are not visible from outside the function. Hence, they have a
localscope.

• The lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetimeof variables inside a function is as long as the function executes.

• They are destroyed once we return from the function. Hence, a function does not remember thevalue
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
ofa variable from its previous calls.
Example:
def my_fun():
x = 10
print("Value inside function:",x)x = 20
my_fun()
print("Value outside function:",x)
Output:
Value inside function: 10 Value
outside function: 20Explanation:
• Here, we can see that the value of x is 20 initially. Even though the function my_fun() changed
thevalue of x to 10, it did not affect the value outside the function.

• This is because the variable x inside the function is different (local to the function) from the one
outside.Although they have the same names, they are two different variables with different scopes.
Python Modules
• Modules refer to a file containing Python statements and definitions.We use modules to break
downlarge programs into small manageable and organized files. Furthermore, modules provide
reusability ofcode.
• We can define our most used functions in a module and import it, instead of copying their
definitionsinto different programs.

Example: Type the following and save it as example.py.


# Python Module exampledef
add(a, b):
result = a + breturn
result
Explanation: Here, we have defined a function add() inside a module named example. The functiontakes in
two numbers and returns their sum.
How to import modules in Python?
• We can import the definitions inside a module to another module or the interactive interpreter in
Python.
• We use the import keyword to do this. To import our previously defined module example, we type
thefollowing in the Python prompt.
• >>> import example

This does not import the names of the functions defined in example directly in the current symbol table. It
only imports the module name example there. Using the module name we can access the function using the
dot . operator.
Example:
>>> example.add(4,5.5)
9.5
Python has lots of standard modules. Refer standard modules in UNIT-1 Material. These files are
in the Lib directory inside the location where you installed Python. There
are various ways to import modules. They are listed below.. 1.Python
import statement
2.import with renaming
3.Python from...import statement
4.import all names

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
1. Python import statement:
• We can import a module using the import statement and access the definitions inside it using the
dotoperator as described above.

Example:
import math
print("The value of pi is", math.pi)
Output:
The value of pi is 3.141592653589793

2. import with renaming:


• We can import a module by renaming it. We have renamed the math module as m. This can save
ustyping time in some cases.
• Note: that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is
thecorrect implementation.

Example:
import math as m
print("The value of pi is", m.pi)
3. Python from...import statement:
• We can import specific names from a module without importing the module as a whole. Here,
weimported only the pi attribute from the math module. In such cases, we don't use the dot operator.
Example:1
from math import pi
print("The value of pi is", pi)

4. import all names:


• We can import all names(definitions) from a module. we can import all the definitions from the
mathmodule. This includes all names visible in our scope except those beginning with an
underscore(privatedefinitions).

• Importing everything with the asterisk (*) symbol is not a good programming practice. This can lead
toduplicate definitions for an identifier. It also hampers the readability of our code.
Example:
from math import * print("The
value of pi is", pi)
Python Package
• We don't usually store all of our files on our computer in the same location. We use a well-
organizedhierarchy of directories for easier access.

• Similar files are kept in the same directory, for example, we may keep all the songs in the
"music"directory. Analogous to this, Python has packages for directories and modules for files.

• As our application program grows larger in size with a lot of modules, we place similar modules in
onepackage and different modules in different packages. This makes a project (program) easy to
manageand conceptually clear.

• Similarly, as a directory can contain subdirectories and files, a Python package can have sub-
packagesand modules.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
• A directory must contain a file named init .py in order for Python to consider it as a package. Thisfile
can be left empty but we generally place the initialization code for that package in this file.

• Here is an example. Suppose we are developing a game. One possible organization of packages
andmodules could be as shown in the figure below.

Importing module from a package:


•We can import modules from packages using the dot (.) operator. For example, if we want toimport
the start module in the above example, it can be done as follows:
import Game.Level.start
•Now, if this module contains a function named select_difficulty(), we must use the full name
toreference it.
Game.Level.start.select_difficulty(2)
•If this construct seems lengthy, we can import the module without the package prefix asfollows.
from Game.Level import start
•We can now call the function simply as follows
start.select_difficulty(2)
•Another way of importing just the required function (or class or variable) from a module with in a
package would be as follows.
from Game.Level.start import select_difficulty
• Now we can directly call this function.
select_difficulty(2)
• Although easier, this method is not recommended. Using the full namespace avoids confusionand
prevents two same identifier names from colliding.

• While importing packages, Python looks in the list of directories defined in sys.path, similar asfor
module search path.

Higher Order Functions


A function is called Higher Order Function if it contains other functions as a parameter or
returns a function as an output i.e, the functions that operate with another function are known
as Higher order Functions. It is worth knowing that this higher order function is applicable
for functions and methods as well that takes functions as a parameter or returns a function as
a result. Python too supports the concepts of higher order functions.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Properties of higher-order functions:
 A function is an instance of the Object type.
 You can store the function in a variable.
 You can pass the function as a parameter to another function.
 You can return the function from a function.
 You can store them in data structures such as hash tables, lists, …
Functions as objects
In Python, a function can be assigned to a variable. This assignment does not call the
function, instead a reference to that function is created. Consider the below example, for
better understanding.
Example:

# Python program to illustrate functions# can be treated as


objects
defshout(text):
returntext.upper()

print(shout('Hello'))

# Assigning function to a variable yell =shout

print(yell('Hello'))
Output:

HELLO
HELLO

Decorators
Decorators are the most common use of higher-order functions in Python. It allows
programmers to modify the behavior of function or class. Decorators allow us to
wrap another function in order to extend the behavior of wrapped function, without
permanently modifying it. In Decorators, functions are taken as the argument into
another function and then called inside the wrapper function.
Syntax:
@gfg_decorator
def hello_decorator():
.
.
.

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
The above code is equivalent to –

def hello_decorator():
.
.
.

hello_decorator = gfg_decorator(hello_decorator)
In the above code, gfg_decoratoris a callable function, will addsome code on
the top of some another callable
function, hello_decoratorfunction and return the wrapper function.
Example:
# defining a decorator
def hello_decorator(func):

# inner1 is a Wrapper function in# which the argument


is called

# inner function can access the outer local# functions like in this case
"func"
def inner1():
print("Hello, this is before functionexecution")

# calling the actual function now# inside the wrapper


function. func()

print("This is after function execution")return inner1

# defining a function, to be called inside wrapperdeffunction_to_be_used():

print("This is inside the function !!")# passing

'function_to_be_used' inside the # decorator to control its behavior

function_to_be_used =hello_decorator(function_to_be_used)# calling the function

function_to_be_used()

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3
Output:
Hello, this is before function executionThis is inside the
function !!
This is after function execution

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3

VKR,VNB&AGK COLLEGE OF ENGINEERING


R20 Python Unit-3

Namespaces and Scope


A namespace is a system that has a unique name for each and every object in Python. An object
might be a variable or a method. Python itself maintains a namespace in the form of a Python
dictionary. Let’s go through an example, a directory-file system structure in computers. Needless
to say, that one can have multiple directories having a file with the same name inside every
directory. But one can get directed to the file, one wishes, just by specifying the absolute path to
the file.
Real-time example, the role of a namespace is like a surname. One might not find a single
“Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice
Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both
first name and surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying to
point to in the code, depending upon the namespace. So, the division of the worditself gives a little
more information. Its Name (which means name, a unique identifier)
+ Space(which talks something related to scope). Here, a name might be of any Python method or
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python Unit-3
variable and space depends upon the location from where is trying to access avariable or a method.
Types of namespaces :
When Python interpreter runs solely without any user-defined modules, methods,
classes, etc. Some functions like print(), id() are always present, these are built-in
namespaces. When a user creates a module, a global namespace gets created, later
the creation of local functions creates the local namespace. The built-in namespace
encompasses the global namespace and the global namespace encompasses the
local namespace.

VKR,VNB&AGK COLLEGE OF ENGINEERING

You might also like