Professional Documents
Culture Documents
Wa0000.
Wa0000.
computing(PYTHON)
IU214122OO27
PYTHON LABORATORY-5
Lambda function:
Map function:
What If I ask you to find a square of the first five odd numbers. You would probably
write something like the following:
squares = []
for n in rangefl, 10, 2):
squares.append(n ** 2)
The loop iterates through 1 to 10 with a step size of 2 and appends the square of
each number to squares. The approach shown above can be improved using list
comprehension but that too will use for loop. So, there's a faster way to do the
same without using explicit for loop. Python's map function does that. It transforms
the given iterable based on the given condition.
Filter function:
Let's say you want to find the odd numbers from a given list. A quick way to
approach this problem is to use a for loop inside a list comprehension.
Python's filter does the same in a faster way. It has the same syntax as the map.
IU2141220027
Programming of scientific
computing(PYTHON)
filter(function, iterable)
It works similarly to the map. It returns a filter object, unlike a map object.
def find_odd(x):
if x % 2 1=0:
return x
nums = [1, 34, 23, 56, 89, 44, 92]
odds = Iist(filter(find_odd, nums))
print(odds)
# Output: [1, 23, 89]
Let us convert this find_odd function to a lambda function and rewrite the code to
make it shorter.
Reduce function:
Lets say you want to compute a sum of the first five integers. You can write
something like the following:
nums = [1, 2, 3, 4, 5]
summ = 0
for num in nums:
summ += num
summ
# Output: 15
The loop iterates through nums and keeps adding all the numbers to summ. Again
to make it pythonic, we have a function, i.e. Reduce.
IU2141220027
Programming of scientific
computing(PYTHON)
returns a single value. Don't worry if you haven't get it yet.
1. Write a Python program to find the triple of all numbers in a given list of
integers.
a = [1Z2Z3Z4Z5]
Output:
IU2141220027
Programming of scientific
computing(PYTHON)
2. Write a Python program to add three given lists using Python map and
lambda.
a = [1,2,3]
b = [2,3,4]
c = [6,7,8]
print(list)ans))
Output:
Sum of three given list is:
ft 12,15]
IU2141220027
Programming of scientific
computing(PYTHON)
names = ["Aarya","Nainir,"Kirtan","Dev"]
listify = list(map(list, names)) print("\n After listify the list of strings are:")
print(listify)
Output:
base = [1,2,3,4,5,6]
index = [2,4,1,2,3,3]
print(result)
Output:
IU2141220027
Programming of scientific
computing(PYTHON)
a = [1Z-2Z3Z-4Z-5Z6Z7Z-8Z9]
print(pos)
Output:
[1, 3Z 6Z1, 9]
a = [1Z-2Z3Z-4Z-5Z6Z7Z-8Z9]
Output:
IU2141220027
Programming of scientific
computing(PYTHON)
7. Write a Python program to filter all the vowels from a given string.
for i in str:
•ri • Il • ii • p| • ii •ll\
if (i== a or i== e or i== i or i== o or i== u ):
print(i)
Output:
IU2141220027