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 Answers 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!
3 Comments
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.
arr[i]- i.e. -arr[2]as the loop variable! You want to dofor x in arr: print(x)for j in arr: print j? Not sure what you're trying to achieve by having arr[i] as the iterating value.