Today I completed 24th Day of #100DayOfcode and #python. Today I also revised python basic with the help of internet and Youtube.
Tried to write some code in python.
New things today I learned were python iterator, python map, python filter, python reduce on youtube and with the help of friend. some simple code today I learned given below.
Some Simple Code On Python Iterator, Filter, Map
Python iterator is an object that can be iterated upon meaning that we can traverse through all the values. Technically, in python , an iterator is an object which implements the iter protocal, which consists of the method __iter__()
and __next()
class TopTen:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if self.num <= 10:
val = self.num
self.num += 1
return val
values = TopTen()
print(values.__next__())
print(values.__next__())
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
numbersSquare = set(result)
print(numbersSquare)
The filter() method constructs an iterator from elements of an iterable for which a function return true.
In simple words, filter() method filters the given iterable with the help of a function that test each element in the iterable to be true or not.
def is_even(n):
return n % 2 == 0
nums = [2,3,4,6,8,6,5,7]
evens =list( filter(is_even,nums))
print(evens)
The reduce (fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in "functools" module.
from functools import reduce
nums = [2,3,4,6,8,6,5,7]
evens =list( filter(lambda n : n% 2 ==0,nums))
double =list(map(lambda n : n*2,evens))
sum = reduce(lambda a, b : a+b ,double)
#print(double)
print(sum)
Day 24 of #100DaysOfCode and #Python
— Durga Pokharel (@mathdurga) January 17, 2021
* More About Python Basic
* Learned About Python Iterator, Map, Filter, Reduce
* Some Code On iterator, filter, Map pic.twitter.com/RWmGydHX34
Top comments (0)