-2

I want to do multiplication using for loop. Here is the code.

a = 4
b = 6
for i in [a,b]:
    i*=2

The values of a and b remain the same. How to make it work?

Chan
  • 3,605
  • 9
  • 29
  • 60
  • `int` objects are immutable; you can't do what you are trying to do. Read https://nedbatchelder.com/text/names.html – chepner Mar 22 '18 at 03:11
  • What values do you want to multiply? – bigbounty Mar 22 '18 at 03:12
  • I would consider "map" with a lambda function. Or just define your own function f(x): return 2*x – Kenny Ostrom Mar 22 '18 at 03:13
  • Sounds like a XY problem. If you only have 2 variables, `a*=2;b*=2` is definitely better. If you have a [variable number of variables](https://stackoverflow.com/questions/1373164), you should use a list or dict and there should be easier ways (list comprehension, dict comprehension) – user202729 Mar 22 '18 at 03:13

2 Answers2

1

int are immutable, so you'll need to rebind a and b to fresh int objects

>>> a = 4
>>> b = 6
>>> a, b = (i*2 for i in [a,b])
>>> a
8
>>> b
12
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Use dictionary:

z = {'i': a, 'j': b}
for k in z.keys():
    z[k] *= 2
a = z['i']
b = z['j']
Mike
  • 133
  • 2
  • 13