Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the map() function?

Tags:

python

I was working with Python, and I noticed that the map() function doesn't really seem to do much. For instance, if I write the program:

mylist = [1, 2, 3, 4, 5]
function = map(print, l)
print(function)

It provides no advantages over:

mylist = [1, 2, 3, 4, 5]
for item in mylist:
    print(item)

In fact, the second option creates fewer variables and seems generally cleaner overall to me. I would assume that map() provides advantages that cannot be seen in an example as simplistic as this one, but what exactly are they?

EDIT: It seems that some people have been answering a different question than the one I intended to ask. The developers who made Python obviously put some work into creating the map() function, and they even decided NOT to take it out of 3.0, and instead continue working on it. What essential function did they decide it served?

like image 331
KnightOfNi Avatar asked Jun 08 '14 21:06

KnightOfNi


People also ask

Why do we need map in Python?

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.

Why do we use map in JavaScript?

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.

What is the function of the map () syntax?

map() method allows you to iterate over an array and modify its elements using a callback function.

Why We Use map function in React JS?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.


1 Answers

It used to be more useful back before list comprehensions. You've probably seen code like

[int(x[2]) for x in l]

Back before list comprehensions, you'd write that as

map(lambda x: int(x[2]), l)

(This was also back before map returned an iterator.)

These days, list comprehensions and generator expressions handle most of what map used to do. map is still cleaner sometimes, particularly when you don't need a lambda. For example, some people prefer

map(str, l)

over

(str(x) for x in l)
like image 141
user2357112 supports Monica Avatar answered Oct 21 '22 08:10

user2357112 supports Monica