Skip to content
Advertisement

python – apply Operation on multiple variables

I know that this is a rather silly question and there are similar ones already answered, but they don’t quite fit, so… How can I perform the same operation on multiple variables in an efficient way, while “keeping” the individual variables? example:

a = 3
b = 4
c = 5
a,b,c *= 2  #(obviously this does not work)
print(a,b,c) 

What I want as the output in this scenario is 6, 8, 10. It is rather important that I can still use changed variables.

Thank you very much for your answers!

Advertisement

Answer

You can use numpy or python lambda function combined with map to do the same.

Using numpy:

In [17]: import numpy as np

In [18]: a = 3
    ...: b = 4
    ...: c = 5
    ...:

In [19]: a,b,c = np.multiply([a, b, c], 2)

In [20]: a
Out[20]: 6

In [21]: b
Out[21]: 8

In [22]: c
Out[22]: 10

Using lambda:

In [23]: a, b, c = list(map(lambda x: x*2, [a, b, c]))

In [24]: a
Out[24]: 12

In [25]: b
Out[25]: 16

In [26]: c
Out[26]: 20

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement