Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements.
Mapping in Python means applying an operation for each element of an iterable, such as a list. For example, let's square a list of numbers using the map() function: numbers = [1, 2, 3, 4, 5] squared_nums = map(lambda x: x ** 2, numbers) print(list(squared_nums))
The map function performs a transformation on each item in an iterable, returning a lazy iterable back. The filter function filters down items in an iterable, returning a lazy iterable back.
class FoodExpert:
def init(self):
self.goodFood = []
def addGoodFood(self, food):
self.goodFood.append(food)
def likes(self, x):
return x in self.goodFood
def prefers(self, x, y):
x_rating = self.goodFood.index(x)
y_rating = self.goodFood.index(y)
if x_rating > y_rating:
return y
else:
return x
After declaring this class , I wrote this code :
>>> f = FoodExpert()
>>> f.init()
>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])
[None, None, None, None, None]
>>> f.goodFood
['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise']
I am unable to understand how the map function is working behind the hood , why is it returning a list with all None
, but when I check f.goodFood
the elements have been added there ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With