-2

I can't understand why in loop variable don't change, but I explicitly try it. So here is my code:

a=[1,2,3]
b=["a","b","c"]
d=[a,b]
for i in d:
    for a in i:
         a*2
         print(a)

And when I run I see :

1
2
3
a
b
c

Instead expected:

2
4
6
aa
bb
cc
Lynx Rufus
  • 99
  • 2
  • 9
  • you should print `2 * a` not a – lmiguelvargasf Feb 04 '17 at 15:00
  • You are not assigning the new value to any variable. Replace `a*2` by `a=a*2`. – Sven Rusch Feb 04 '17 at 15:00
  • The line `a*2` gets "lost", it doesn't change the value of `a`. To do that you'd need to either reassign `a` its new value by doing `a = a * 2` or just print the desired value by doing `print a * 2`. Also, you are using the variable `a` for both the array and the inner variable in the second loop. Avoid this at all costs. – dabadaba Feb 04 '17 at 15:02
  • 1
    by the way I don't understand why people are downvoting this. Sure, it's an absolutely basic question, but for a person who is clearly completely new to programming, I'd say it's a totally legit question. – dabadaba Feb 04 '17 at 15:03
  • Rather than being a duplicate (the other question is about an entirely different confusion), this should have been closed as a typo. The expected behaviour makes no sense at all. – Karl Knechtel Oct 02 '22 at 00:07

3 Answers3

1

In order to change the a when iterating i, you must assign the value to the variable.

so instead of

for a in i:
    a*2
    print(a)

try

for a in i:
    a = a*2
    print(a)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
K-man
  • 353
  • 1
  • 13
0

Because you are not assigning value to the variable. It will change if you do a = a*2, instead of just a*2. Try this in python shell:

>>> a=[1,2,3]
>>> b=["a","b","c"]
>>> d=[a,b]
>>> for i in d:
...     for a in i:
...         a=a*2
...         print(a)
... 
2
4
6
aa
bb
cc
>>>
its me
  • 127
  • 2
  • 8
0
a=[1,2,3]
b=["a","b","c"]
d=[a,b]
for i in d:
    for a in i:
         a=a*2 # change this line like that
         print(a)