0% found this document useful (0 votes)
69 views

Python Unit 2

Uploaded by

Yukthi Raj S. N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Python Unit 2

Uploaded by

Yukthi Raj S. N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

PYTHON PROGRAMMING

UNIT-II:
•LIST: BASIC LIST OPERATIONS, LIST ITERATION AND COMPREHENSIONS, INDEXING, SLICING, TWO
DIMENSIONAL LISTS, ITERATING THROUGH TWO DIMENSIONAL LISTS.
•BASIC DICTIONARY OPERATIONS, CHANGING DICTIONARIES IN PLACE, METHODS, EXAMPLE: MOVIE
DATABASE.
•TUPLES AND SETS (PROPERTIES, OPERATORS, AND METHODS).
•USER-DEFINED FUNCTIONS, LAMBDA FUNCTION, ZIP FUNCTION, PARAMETER PASSING (THRUSTING
MUTABLE AND IMMUTABLE PARAMETERS).
•RECURSION, MEMORY MANAGEMENT DURING RECURSIVE FUNCTION CALLS. GLOBAL VERSUS LOCAL
NAMESPACES.
List
• List is a sequence of values called items or elements.
• The elements can be of any data type.
• Lists are ordered.
• Lists can contain any type of data, including integers, strings,
and even other lists.
• List elements can be accessed by index.
• Lists are mutable which means their elements can be changed.
• The list is a most versatile data type available in Python which
can be written as a list of comma-separated values(items)
between square brackets[].
2
Creating a List
• A list is created by place all the items(elements) inside a
square bracket[], separated by commas.
• Eg.
• My_list=[1,2,4,5]
• My_list=[1,”Hello”,3.4]
• My_list=[] #empty list
• My_list=[“welcome”,[3,5,6]] #nested list

3
Access items from a List
• The items in a list are ordered, and each item has an index
indicating its position in the list.
• The first item in a list is at index 0, the second at index 1, and so
on.
• Eg: whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
whales[0]
5
whales[1]
4
whales[12]
1
4
Access items from a List
Python also lets us index backward from the end of a list. The last
item is at index -1, the one before it at index -2, and so on.
whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
whales[-1]
3
whales[-2]
1
whales[-14]
5
whales[-15]
5
Modifying Lists
nobles = ['helium', 'none', 'argon', 'krypton', 'xenon', 'radon']

nobles[1] = 'neon’ #modifying the list

nobles
['helium', 'neon', 'argon', 'krypton', 'xenon', 'radon']

6
Operations on Lists
Function Description
len(L) Returns the number of items in list L
max(L) Returns the maximum value in list L
min(L) Returns the minimum value in list L
sum(L) Returns the sum of the values in list L
sorted(L) Returns a copy of list L where the items are in order
from smallest to largest (This does not mutate L.)

7
Operations on Lists
half_lives=[887.7,24100.0,6563.0,14, 373300.0]

len(half_lives) sum(half_lives)
5 404864.7

max(half_lives) sorted(half_lives)
373300.0 [14, 887.7, 6563.0, 24100.0, 373300.0]

min(half_lives) half_lives
14 [887.7, 24100.0, 6563.0, 14, 373300.0]

8
Operators + * and del
Example-1 Example-2 Example-3
original = ['H', 'He', 'Li’] metals = ['Fe', 'Ni'] metals = ['Fe', 'Ni']
final = original + ['Be'] metals * 3 del metals[0]
final ['Fe', 'Ni', 'Fe', 'Ni', 'Fe', metals
['H', 'He', 'Li', 'Be'] 'Ni’] ['Ni']

9
List Methods

10
List Methods
L.extend(v)
Appends the items in v to L

Eg:
colors = ['red', 'orange', 'green']
colors.extend(['black', 'blue'])
colors
['red', 'orange', 'green', 'black', 'blue']

11
List Methods
L.append(v)
Append value v to List L

Eg:
Colors=['red', 'orange', 'green', 'black', 'blue']
colors.append('purple')
colors
['red', 'orange', 'green', 'black', 'blue', 'purple']

12
List Methods
L.insert(I, v)
Inserts value v at index i in list L, shifting subsequent items to make
room

Eg:
colors=['red', 'orange', 'green', 'black', 'blue', 'purple']
colors.insert(2, 'yellow')
colors
['red', 'orange', 'yellow', 'green', 'black', 'blue', 'purple']

13
List Methods
L.remove(v)
removes first occurance of value v from list L

Eg:
colors=['red', 'orange', 'yellow', 'green', 'black', 'blue', 'purple']
colors.remove('black’)

colors
['red', 'orange', 'yellow', 'green', 'blue', 'purple']

14
List Methods
L.sort()

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort()

print(thislist)
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

15
Iteration
different ways to iterate over a list in Python
• Using for loop
• Print all items by referring to their index number
• Print all items, using a while loop
• List Comprehension

# Python code to iterate over a list


list = [1, 3, 5, 7, 9]

# Using for loop


for i in list:
print(i)

16
Iteration
Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])

apple
banana
cherry
17
Iteration
Print all items, using a while loop to go
through all the index numbers

thislist = ["apple", "banana", "cherry"]


i=0
while i < len(thislist):
print(thislist[i])
i=i+1

apple
banana
cherry
18
List Comprehension
•Looping Using List Comprehension
•List Comprehension offers the shortest syntax for looping
through lists
The Syntax
newlist =
[expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
apple
banana
cherry
19
Without List Comprehension
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)

['apple', 'banana', 'mango']

20
With List Comprehension
fruits = ["apple", "banana", "cherry", "kiwi",
"mango"]
newlist = [x for x in fruits if "a" in x]

print(newlist)
['apple', 'banana', 'mango']

21
List Comprehension
fruits = ["apple", "banana", "cherry",
"kiwi", "mango"]
newlist = [x for x in fruits if x !=
"apple"]
print(newlist)

Output:
['banana', 'cherry', 'kiwi', 'mango'] 22
List Comprehension - Exercise
newlist = [x for x in range(10) if x < 5]
print(newlist)
Output:
[0, 1, 2, 3, 4]

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = [x.upper() for x in fruits]
print(newlist)
Output:
['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
23
List Comprehension - Exercise
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x if x != "banana" else "orange" for x in fruits]

print(newlist)
Output:
['apple', 'orange', 'cherry', 'kiwi', 'mango']

24
List Comprehension - Exercise
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist)
Output:
['hello', 'hello', 'hello', 'hello', 'hello']

25
Slicing Lists
• The first index in the slice is the starting point.
• The second index is one more than the index of the last item we want to
include.

phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']


useful_markers = phenotypes[0:4]#slicing from 0th to 3rd element
useful_markers
['Emb', 'Him', 'Unc', 'Lon’]

26
Slicing Lists
celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']

The first index can be omitted if we want to slice from the beginning of the list
celegans_phenotypes[:4]
['Emb', 'Him', 'Unc', 'Lon']

the last index can be omitted if we want to slice to the end:


celegans_phenotypes[4:]
['Dpy', 'Sma']

27
Two-dimensional Lists
What if elements in a list are lists?
matrix = [ [1, 3, 5], [2, 4, 6] ]
print(matrix[0]) #gives you the entire 0th-element, which is [1, 3, 5]
# How do we access an element inside of the inner list?
# Use a second set of brackets to access an inner list’s elements
print(matrix[0][1]) #gives you 3

28
Two-dimensional Lists
Another way to show a 2-D list
matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ]
# Each inner list is a row
# Within each row are column elements # Access individual
elements by using matrix[ROW][COL]

29
Two-dimensional Lists
Changing elements
matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ]
matrix[2][1] = 5 #changes the row-2, col-1 to 0
#[ [1, 5, 9], # [2, 4, 6], # [8, 0, 3] ]

30
Two-dimensional Lists
len() and matrices matrix = [ [1, 3, 5], [2, 4, 6] ]
print(len(matrix)) #len() will return 2
print(len(matrix[1])) #len() will return 3

31
Two-dimensional Lists
Looping!
matrix = [ [1, 5, 9], [2, 4, 6], [8, 5, 3] ]
for r in range(3):
#iterate through each row index
for c in range(3):
#iterate through each col index
print(matrix[r][c])
#access the specific element
32
Two-dimensional Lists
elements = [['Li', 'Na', 'K'], ['F', 'Cl', 'Br']]
for inner_list in elements:
print(inner_list)
...
['Li', 'Na', 'K']
['F', 'Cl', 'Br']

33
Two-dimensional Lists
elements = [['Li', 'Na', 'K'], ['F', 'Cl', 'Br']]
for inner_list in elements:
for item in inner_list:
print(item)
Li
Na
KF
Cl
Br
34
Dictionaries
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered, mutable and do
not allow duplicates.
• Ordered: items have a defined order, and that order will not
change.
• Mutable: we can change, add or remove items after the
dictionary has been created.
• Not allow duplicates: Cannot have two items with the same
key
35
Dictionaries
• Example: Create Dictionaries
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

36
Dictionaries- Accessing Items
• You can Access items using key and get method.

thisdict = { "brand": "Ford“, "model": "Mustang",


"year": 1964 }
x = thisdict["model"]
print(x)

Output: Mustang
37
Dictionaries- Accessing Items
thisdict = { "brand": "Ford",
"model": "Mustang",
"year": 1964 }
x = thisdict.get("model")
print(x)

Output:
Mustang
38
Dictionaries-Methods
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
39
Dictionaries-Methods
1) The clear() method removes all the elements from
a dictionary.

car ={"brand": "Ford", "model": "Mustang",


"year": 1964 }
car.clear()
print(car)
Output: {}
40
Dictionaries-Methods
2) The copy() method returns a copy of the specified
dictionary.
car = {"brand": "Ford","model": "Mustang",
"year": 1964}
x = car.copy()
print(x)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
41
Dictionaries-Methods
3) The fromkeys() method returns a dictionary with
the specified keys and the specified value.
x = ('key1', 'key2', 'key3')
y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Output:
{'key1': 0, 'key2': 0, 'key3': 0}
42
Dictionaries-Methods
4) The get() method returns the value of the item
with the specified key.
car = {"brand": "Ford", "model": "Mustang",
"year": 1964}
x = car.get("model")
print(x)
Output:
Mustang
43
Dictionaries-Methods
5) The items() method returns a view object. The view
object contains the key-value pairs of the dictionary, as
tuples in a list.
car = {"brand": "Ford", "model": "Mustang",
"year": 1964}
x = car.items()
print(x)
Output: dict_items([('brand', 'Ford'),
('model', 'Mustang'), ('year', 1964)])
44
Dictionaries-Methods
6) The keys() method returns a view object. The view
object contains the keys of the dictionary, as a list.
car = { "brand": "Ford","model": "Mustang",
"year": 1964 }
x = car.keys()
print(x)
Output:
dict_keys(['brand', 'model', 'year'])
45
Dictionaries-Methods
7) The pop() method removes the specified item from
the dictionary.
car = {"brand": "Ford", "model": "Mustang",
"year": 1964 }
car.pop("model")
print(car)
Output:
{'brand': 'Ford', 'year': 1964}
46
Dictionaries-Methods
8) The popitem() method removes the item that was last
inserted into the dictionary.
car = {"brand": "Ford","model": "Mustang",
"year": 1964}
car.popitem()
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
47
Dictionaries-Methods
9) The setdefault() method returns the value of the item
with the specified key.
car = {"brand": "Ford","model": "Mustang",
"year": 1964}
x = car.setdefault("model")
print(x)
Output:
Mustang
48
Dictionaries-Methods
10) The update() method inserts the specified items 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'}
49
Dictionaries-Methods
11) The values() method returns a view object. The view
object contains the values of the dictionary, as a list.
car = {"brand": "Ford", "model": "Mustang",
"year": 1964 }
x = car.values()
print(x)
Output:
dict_values(['Ford', 'Mustang', 1964])
50
Neated Dictionaries
A dictionary can contain dictionaries, this is called nested
dictionaries.
myfamily = {
"child1" : { "name" : "Emil“, "year" : 2004 },
"child2" : { "name" : "Tobias“, "year" : 2007 },
"child3" : { "name" : "Linus“, "year" : 2011 }
}
print(myfamily)
Output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name':
'Linus', 'year': 2011}}

51
Sets
• Sets are sequence data type in python.
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable,
and unindexed.
• Unordered : means that the items in a set do not have a defined
order.
• Immutable: Set items are unchangeable, meaning that we cannot
change the items after the set has been created.
• Duplicates not allowed: Sets cannot have two items with the
same value.

52
Sets
• Create a set
thisset = {"apple", "banana", "cherry"}
print(thisset)
• Output:
{'banana', 'apple', 'cherry'}

set1 = {"abc", 34, True, 40, "male"}


print(set1)
• Output:
{True, 34, 40, 'male', 'abc'}
53
Sets
• Duplicates Not Allowed
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
• Output:
{'banana', 'apple', 'cherry'}

54
Sets
• Access Items: You cannot access items in a set by referring to an
index or a key.
• You can access items of set using for loop.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
apple
banana
cherry
55
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other,
specified set(s)

56
Set Methods
Method Description
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_upd inserts the symmetric differences from this set and another
ate()
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

57
Set Methods
1) The add() method adds an element to the set.
• If the element already exists, the add() method does not add
the element.

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)
• Output:
{'banana', 'apple', 'cherry', 'orange'}

58
Set Methods
2) The clear() method removes all elements in a set.

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset)
• Output:
Set()

59
Set Methods
3) The copy() method copies the set.

thisset = {"apple", "banana", "cherry"}


X=thisset.copy()
print(x)
• Output:
{'cherry', 'banana', 'apple'}

60
Set Methods
4) The difference() method returns a set that contains the
difference between two sets.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
• Output:
{'cherry', 'banana‘}

61
Set Methods
5) The difference_update() method removes the items that exist in both
sets.
• difference() method returns a new set, without the unwanted items,
and the difference_update() method removes the unwanted items
from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference_update(y)
print(z)
• Output:
{'cherry', 'banana‘}
62
Set Methods
6) The discard() method removes the specified item from the
set.

thisset = {"apple", "banana", "cherry"}


thisset.discard("banana")
print(thisset)
• Output:
{'cherry', ‘apple‘}

63
Set Methods
7) The intersection() method returns a set that contains the
similarity between two or more sets.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
• Output:
{‘apple‘}

64
Set Methods
8) The intersection_update() method removes the items that is not
present in both sets.
• the intersection() method returns a new set, without the unwanted
items, and the intersection_update() method removes the unwanted
items from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
• Output:
{‘apple‘}
65
Set Methods
9) The isdisjoint() method returns True if none of the items are
present in both sets, otherwise it returns False.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
• Output:
True

66
Set Methods
10) The issubset() method returns True if all items in the set
exists in the specified set, otherwise it returns False.

x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
• Output:
True

67
Set Methods
11) The issuperset() method returns True if all items in the
specified set exists in the original set, otherwise it returns
False.

x = {"f", "e", "d", "c", "b", "a"}


y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)
• Output:
True
68
Set Methods
12) The pop() method removes a random item from the set.

fruits = {"apple", "banana", "cherry"}


fruits.pop()
print(fruits)
• Output:
{'apple', 'cherry'}

69
Set Methods
13) The remove() method removes the specified element from
the set.

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")
print(fruits)
• Output:
{'apple', 'cherry'}

70
Set Methods
14) The symmetric_difference() method returns a set that
contains all items from both set, but not the items that are
present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
• Output:
{'google', 'banana', 'microsoft', 'cherry'}

71
Set Methods
15) The symmetric_difference_update() method updates the
original set by removing items that are present in both sets, and
inserting the other items.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
• Output:
{'cherry', 'banana', 'google', 'microsoft'}

72
Set Methods
16) The union() method returns a set that contains all items
from the original set, and all items from the specified set(s).

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
• Output:
{'microsoft', 'cherry', 'google', 'banana', 'apple'}

73
Set Methods
17) The update() method updates the current set, by adding
items from another set.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.update(y)
print(x)
• Output:
{'apple', 'google', 'cherry', 'banana', 'microsoft'}

74
Tuples
• Tuples are sequence data types.
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Ordered: items have a defined order, and that order will not
change.
• Unchangeable:Tuples are unchangeable, meaning that we
cannot change, add or remove items after the tuple has been
created.
• Tuples are indexed, they can have items with the same value
• Tuples are written with round brackets.
75
Tuples
How to Create tuple?
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")

76
Tuples
• Access Tuple Items: You can access tuple items by
referring to the index number, inside square brackets.

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])
• Output:
• banana

77
Tuples
• Access Tuple Items: You can access tuple items by
referring to the index number, inside square brackets.
• You can also use negative indexing.

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])
• Output:
• banana

78
Tuples
• Range of Indexes: You can specify a range of indexes
by specifying where to start and where to end the
range.

thistuple = ("apple", "banana", "cherry", "orange",


"kiwi", "melon", "mango")
print(thistuple[2:5])
• Output:
('cherry', 'orange', 'kiwi')
79
Tuples
• Update tuple: Tuples are unchangeable, meaning that you cannot
change, add, or remove items once the tuple is created.
• You can convert the tuple into a list, change the list, and convert
the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
• Output:("apple", "kiwi", "cherry")
80
Tuples
• Add items into tuple:
• you can convert it into a list, add your item(s), and convert it
back into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
• Output:
• ('apple', 'banana', 'cherry', 'orange')
81
Tuples
• Unpacking a Tuple: When we create a tuple, we normally
assign values to it. This is called "packing" a tuple.
• Packing example:

fruits = ("apple", "banana", "cherry")


print(fruits)
• Output:
• ('apple', 'banana', 'cherry')

82
Tuples
• Unpacking a Tuple: In Python, we are also allowed to extract
the values back into variables. This is called "unpacking“.
• Packing example:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
• Output: apple banana cherry

83
Tuples
• Join Two Tuples: To join two or more tuples you can use
the + operator.

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
• Output:
('a', 'b', 'c', 1, 2, 3)

84
Tuples
• Multiply Tuples

fruits = ("apple", "banana", "cherry")


mytuple = fruits * 2
print(mytuple)
• Output:
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

85
Tuples
• Tuple Methods:
1) The count() method returns the number of times a specified
value appears in the tuple.

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
• Output:
2

86
Tuples
• Tuple Methods:
2) The index() method finds the first occurrence of the specified
value.

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
• Output:
3

87
User defined functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• All the functions that are written by any of us is called as
user-defined functions.
• Creating a Function: In Python a function is defined using
the def keyword.
def my_function():
print("Hello from a function")

88
User defined functions
• Calling a Function:
def my_function():
print("Hello from a function")
my_function()

Output:
Hello from a function

89
User defined functions
• Argument: Information can be passed into functions as
arguments(parameters).
def evenOdd( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output: even odd
90
Lambda functions
• A lambda function is a small anonymous function means that
the function is without a name.
• A lambda function can take any number of arguments, but
can only have one expression.
• Syntax:
lambda arguments : expression
• Example:
x = lambda a: a + 10
print(x(5))
• Output: 15
91
Lambda functions
• Lambda Examples:
x = lambda a, b: a * b
print(x(5, 6))
• Output: 30

x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
• Output: 13

92
Lambda functions
With lambda function Without lambda function

Supports single-line sometimes Supports any number of lines inside


statements that return some value. a function block

Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.

Using the lambda function can


We can use comments and function
sometime reduce the readability of
descriptions for easy readability.
code.

93
Zip function
• Python zip() method takes iterable containers and returns a
single iterator object, having mapped values from all
the containers.
• If the passed iterables have different lengths, the iterable
with the least items decides the length of the new iterator.
• It is used to map the similar index of multiple containers so
that they can be used just using a single entity.
• As a container you can use string, list, set, and tuples.

94
Zip function
• Syntax:
zip(iterator1, iterator2, iterator3 ...)
• Example:
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")
x = zip(a, b)
print(tuple(x))
• Output:
• (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
95
Recursion
• The term Recursion can be defined as the process of defining
something in terms of itself.
• In simple words, it is a process in which a function calls itself.
• Advantages of using recursion:
1. A complicated function can be split down into smaller
sub-problems utilizing recursion.
2. Sequence creation is simpler through recursion than utilizing
any nested iteration.
3. Recursive functions render the code look simple and
effective.
96
Recursion
• Disadvantages of using recursion:
1. A lot of memory and time is taken through recursive calls
which makes it expensive for use.
2. Recursive functions are challenging to debug.
3. The reasoning behind recursion can sometimes be tough to
think through.

97
Recursion: Program to print factorial
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num=int(input('Enter number:'))
#num = 3
print('The factorial is:')
print(factorial(num))
98
Recursion: Program to print factorial
• Output:
Enter number:4
The factorial is:
24

99
Recursion: Program to print factorial

100
Recursion: Program to print fibonacci series
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms=int(input('Enter how many terms:'))
#n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
101
Recursion: Program to print fibonacci series
• Output:
Enter how many terms:6
Fibonacci series:
0
1
1
2
3
5
102
Questions From Unit-2
1. What is list in python? Explain operations on lists.
2. Explain List Methods with example.
3. What is List Comprehension? Explain with example.
4. What is two-dimensional List? Explain with Example.
5. What is Dictionary in python? Explain dictionary Methods with example.
6. What is set in python? Explain set Methods with example.
7. What is Tuple in python? Explain Unpacking in tuples.
8. How to add items and update items in tuple?
9. What is Tuple in python? Explain Tuple Methods with example.
10. What is User defined function in Python? Explain with example.
11. What is Lambda function in Python? Explain with example.
103
12. What is recursion in Python? Write advantages and disadvantages of recursion.
The End

104

You might also like