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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With