Professional Documents
Culture Documents
Wa0001.
Wa0001.
computing(PYTHON)
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.appendfn ** 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)
5
filterffunction, iterable)
It works similarly to the map. It returns a filter object, unlike a map object.
def find_odd(x):
ifx%2 !=0:
return x
nums = [1, 34, 23, 56, 89, 44, 92]
odds = list(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:
Let's 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)
The reduce applies a function cumulatively on all the items of an iterable and
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 = [1,2,3,4,5]
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:
12,15]
IU2141220027
Programming of scientific
computing(PYTHON)
names = ["Aarya"/,Nainir7'Kirtan,7'Dev"]
listify = list(map(list? names)) print("\n After listify the list of strings are:")
print(listify)
Output:
IU21412200267
Programming of scientific
computing(PYTHON)
base = [1,2,3,4,5,6]
index = [2,4,1,2,3,3]
print(result)
Output:
IU2141220027
Programming of scientific
computing(PYTHON)
a = [1,-2,3,-4,-5,6,7,-8,9]
print(pos)
Output:
[1, 3, 6, 7, 9]
a = [1,-2,3,-4,-5,6,7,-8,9]
Output:
Even Numbers from the List a re: [-2, -4, 6> -8]
IU2141220027
Programming of scientific
computing(PYTHO
7. Write a Python program to filter all the vowels from a given string.
for i in str:
Output: