Yes, it is fine to read it there. This is because when you create a for
loop, internally, it has a mechanism to create the indexer
for you (in your case being i
) and then increases it one by one by assigning new value to it every time. Thus, you can use the i
after the for
loop. Thus after:
a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
i
isn't really dropped. To drop i
, you can use del
keyword:
a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
del i #deleted here
print i # now this will give you error!
While to replace is, you just simply need to redefine it:
a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
i = [] #now this is a list, not an integer anymore
print i # now this will give you different result: []
Similarly, for example, if you create a list in an if block:
if i == 0: #suppose you really enter this block
a = [] #a is created here
a.append(b) #but a can be used here, assuming the previous if is really entered
This is just how Python works.
Some related posts: