2

In Python we have the map method that allows us to perform a callable on each element of an iterable. Example:

requests = map(create_update_request, locations)

This is quite easy (although some argue it's more "pythonic" to use list comprehensions, I'd say it depends on the use-case). However, to my knowledge, map only works if it's single-input methods, e.g.

def create_update_request(location_id: int):
    ...

locations = [1, 2, 3]

requests = map(create_update_request, locations)

What if the callable we want to parse takes input, that is contained in the iterable through a tuple?

def create_update_request(location_id: int, item: dict):
    ...

locations = [(1, {"name": "foo"}),
             (2, {"name": "bar"}),
             (3, {"name": "baz"})]

#requests = map(create_update_request, locations) does not work any more!
requests = [create_update_request(location_id, item) for (location_id, item) in locations] # A
requests = [create_update_request(*args) for args in locations] # B

Then we are forced into a list comprehension that triggers everything being loaded to memory. Is there an elegant way around this?

1 Answer 1

2

You can use itertools,

from itertools import starmap
requests = starmap(create_update_request, locations)

Of course, if the lack of lazy iteration was your concern, you could have always used a generator expression

requests = (create_update_request(*args) for args in locations)
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly the one I didn't know of, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.