Wednesday 15 May 2013

python - variable doesn't reset in while loop with function -



python - variable doesn't reset in while loop with function -

i have never come across before , wonder if has solution. have while loop function within returns integer. function takes string , list. first iteration of while loop returns right reply on subsequent iterations list seems empty though function not alter list in way. if seek reset list after function in while loop new list seems empty. seems unusual behavior. explanation whats going on much appreciated. code of function within loop quite long @ stage avoid posting it. if requested post.

spectrum = [1,2,3,4,5,6] leaderboard = ['zzz','xxx','yyy'] pep_scores = [] j=0 original_spectrum = spectrum print len(original_spectrum) while j < len(leaderboard): x= linear_score(leaderboard[j],spectrum) #this function doesn't alter spectrum print leaderboard[j], x spectrum = original_spectrum #should reset spectrum though shouldn't necessary print len(spectrum), len(original_spectrum) #prints 2 empty lists pep_scores.append(x) #appends right score on 1st iteration , '0' others j=j+1

i had added print statements seek resolve problem, original code did not contain 'original_spectrum = spectrum' or 'spectrum = original_spectrum' in while loop. don't understand why after 1 iteration 'origninal_spectrum' empty list. haven't posted function because cannot see how causing problem. please inquire if need more information.

its because of define spectrum outside function , scope global , , when pass spectrum function name of list changes on alter globally not local in function ! , note mutable (like lists) objects . (note : labels pointer special memory addresses ) (your re-create command original_spectrum = spectrum create 2 label 1 object !!! )

for improve understanding see below illustration :

>>> a=[1,2,3] >>> def f(s): ... s.remove(1) ... >>> f(a) >>> [2, 3] >>> def f(s): ... s+=[1,2] ... >>> f(a) >>> [2, 3, 1, 2]

now have 2 selection :

make re-create of spectrum , pass function :

copy_spectrum = spectrum[:]

define spectrum within function , 1 outside global usage !

python list function while-loop

No comments:

Post a Comment