-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
5
  • you should print 2 * a not a Commented Feb 4, 2017 at 15:00
  • You are not assigning the new value to any variable. Replace a*2 by a=a*2. Commented Feb 4, 2017 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. Commented Feb 4, 2017 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. Commented Feb 4, 2017 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. Commented Oct 2, 2022 at 0:07

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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
>>>

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.