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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
sushi
  • 274
  • 1
  • 4
  • 13

1 Answers1

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • May I ask what the * is for in the zip function? – sushi Aug 12 '22 at 19:16
  • @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". – wjandrea Aug 12 '22 at 19:49