0
name='ABCDE'
length=len(name)

for i in range(0,length):
    print(name[i],'\t',end='')
    print(i, '\t', end='')
    i+=1
    print(i,'\t',end='')
    print('hello')

Output:
A   0   1   hello
B   1   2   hello
C   2   3   hello
D   3   4   hello
E   4   5   hello

I am not able to understand the second line of output. In the second iteration the value of i should again be incremented in the for loop and the output should be:

C  2  3  hello

and so on in other iteration.

James Z
  • 12,209
  • 10
  • 24
  • 44
Shivank
  • 3
  • 2

1 Answers1

0

If I understand the question correctly, you're assuming the

i+=1

will effect i for the next iteration.

The syntax for i in range(): in python means that at the beginning of each iteration cycle, i will take on the next value provided by range(), regardless of an assignment within the body.

In your case, you have

range(0, length)

Which evaluates to:

range(0,5) # == [0,1,2,3,4]

Thus i takes on the values 0 through 4.

To convince yourself, try this:

for i in range(0,5):
    print(i)
    i = 1000 # any number

which prints:

0
1
2
3
4

See Scope of python variable in for loop

vapurrmaid
  • 2,287
  • 2
  • 14
  • 30