1

I'm newbie in python. I don't understand the output of following python program.

arr = []
for i in range(3):
    arr.append(i * 2)
for arr[i] in arr:
    print arr[i]

Output:

0
2
2 // Why also print 2?? 

Here, An array elements print twice time 2. This is really weird. Please someone help me to clear my doubt. Why program print twice time 2?

2
  • because you're using the arr[i] - i.e. - arr[2] as the loop variable! You want to do for x in arr: print(x) Commented Oct 8, 2017 at 6:48
  • What happens if you change the second loop to for j in arr: print j? Not sure what you're trying to achieve by having arr[i] as the iterating value. Commented Oct 8, 2017 at 6:49

2 Answers 2

2

This happens because your second loop is using the array itself as the loop variable, overwriting the last value. It should have been written like this:

for x in arr:
    print x

PS. Since you're just starting in Python: Switch to Python 3 today!

Sign up to request clarification or add additional context in comments.

3 Comments

python 3 also, print same output.
That's right. There is no difference between Python 2 and 3 with respect to your question, but you should switch because of several important things that do differ.
@rsp I would suggest to keep a keen eye on "both" versions of Python (they aren't different languages!). There is a lot of code in Python 2, and there will be yet more, for a long while. But it may well be a good idea to focus on 3, unless you have an immediate need for 2.
2

What for arr[i] in arr: does is that it reassigns the first and then second element of arr to arr[i] which at that point is arr[2]. That is why your first and second elements of arr are unchanged but the last one has the value of the second.

A for loop in Python loops through elements of an iterable, i.e. your loop will literally fetch element by element like @Alexis explained. In this case it means it will return each element of arr and assign it to arr[i]. It will do that for the last element too - leaving it unchanged but already equal to the second element of arr.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.