0

With Python, I can assign multiple variables like so:

a, b = (1, 2)
print(a)
print(b)
# 1
# 2

Can I do something similar with the map function?

def myfunc(a):
  return (a+1, a-1)
  
a_plus_one, a_minus_one = map(myfunc, (1, 2, 3))
# or
a_plus_one, a_minus_one = list(map(myfunc, (1,2,3)))

print(a_plus_one)
print(a_minus_one)

These attempts give me too many values to unpack error.

Edit:

Desired output is two new lists.

a_plus_one = (2, 3, 4)
a_minus_one = (0, 1, 2)
0

1 Answer 1

3

It looks like you're misunderstanding how map works. Look at list(map(myfunc, (1,2,3))):

[(2, 0), (3, 1), (4, 2)]

You want to transpose that using zip:

>>> a_plus_one, a_minus_one = zip(*map(myfunc, (1,2,3)))
>>> a_plus_one
(2, 3, 4)
>>> a_minus_one
(0, 1, 2)

For more info: Transpose list of lists

Sign up to request clarification or add additional context in comments.

2 Comments

May I ask what the * is for in the zip function?
@siushi It turns an iterable (the map) into separate arguments. For more info, check the link, which also has its own link under "Unpacked argument lists".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.