Python Assign Multiple Variables with Map Function

Question:

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)
Asked By: siushi

||

Answers:

Yes you can. You are passing 3 values, but getting only two variable names. This causes the problem. Either add one more variable name, or get rid of one value.

Answered By: Ciastelix

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

Answered By: wjandrea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.