Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python `map` and arguments unpacking

I know, that

map(function, arguments) 

is equivalent to

for argument in arguments:     function(argument) 

Is it possible to use map function to do the following?

for arg, kwargs in arguments:     function(arg, **kwargs) 
like image 753
Radosław Miernik Avatar asked Jun 01 '13 15:06

Radosław Miernik


People also ask

What is argument unpacking in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

How do I unpack a map object?

Use the Iterable Unpacking Operator * to Convert a Map Object Into a List in Python. In Python, the term unpacking can be defined as an operation whose primary purpose is to assign the iterable with all the values to a List or a Tuple, provided it's done in a single assignment statement.

How do you unpack a list in an argument in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

How do you unpack a range in Python?

Unpacking in Python refers to assigning values in an iterable object to a tuple or list of variables for later use. We can perform unpacking by using an asterisk ( * ) before the object we would like to unpack.


1 Answers

You can with a lambda:

map(lambda a: function(a[0], **a[1]), arguments) 

or you could use a generator expression or list comprehension, depending on what you want:

(function(a, **k) for a, k in arguments) [function(a, **k) for a, k in arguments] 

In Python 2, map() returns a list (so the list comprehension is the equivalent), in Python 3, map() is a generator (so the generator expression can replace it).

There is no built-in or standard library method that does this directly; the use case is too specialised.

like image 103
Martijn Pieters Avatar answered Oct 07 '22 09:10

Martijn Pieters