reliable to read loop variable after loop in Python -
this question has answer here:
- short description of scoping rules? 7 answers
is safe read loop variable after loop (using python 2)? purpose check how many iterations in loop done.
here code show idea:
a=[1,2,3,4,5] in range(len(a)): if a[i] == 2: break print # output 1, safe read here?
yes, fine read there. because when create for loop, internally, has mechanism create indexer (in case being i) , increases 1 one assigning new value every time. thus, can use i after for loop. after:
a=[1,2,3,4,5] in range(len(a)): if a[i] == 2: break i isn't dropped. drop i, can use del keyword:
a=[1,2,3,4,5] in range(len(a)): if a[i] == 2: break del #deleted here print # give error! while replace is, need redefine it:
a=[1,2,3,4,5] in range(len(a)): if a[i] == 2: break = [] #now list, not integer anymore print # give different result: [] similarly, example, if create list in if block:
if == 0: #suppose enter block = [] #a created here a.append(b) #but can used here, assuming previous if entered this how python works.
some related posts:
Comments
Post a Comment