Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map in Python with multiple arguments, including one with a default value

I am using Python3.6 and am trying to figure out ways in which we can use map with multiple arguments.

When I run,

def multiply(x, y, z):
    return x * y * z

products = map(multiply, [3,6], [1,8], [3,5])

list(products) returns [9, 240] as expected

However, when I specify a default value for z,

def multiply(x, y, z = [3,5]):
    return x * y * z

products = map(multiply, [3,6], [1,8])

list(product) returns

[[3, 5, 3, 5, 3, 5],
 [3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5]]

Why does Python differ in the way it runs map in the two scenarios?

like image 826
Isaac Avatar asked Apr 27 '26 21:04

Isaac


1 Answers

Try:

l=iter([3,5])
def multiply(x, y, z = l):
    return x * y * next(z)

products = map(multiply, [3,6], [1,8])

Then list(products) would be: [9, 240]

Explanation:

Your code doesn't work because you're multiplying a number with a list (so basically it will be a list repeated n times), you need to get always the next value, so do next to the iter of the list

See: Python: next() function

like image 86
U12-Forward Avatar answered Apr 29 '26 10:04

U12-Forward