Python - Why is my list not being modified outside the scope of this method? How do I modify my code so that it is? -
i have following method:
def instances(candidate, candidates): count = candidates.count(candidate) # removing candidate candidates. # list(filter(candidate.__ne__, candidates)) return {candidate: count}
its intended purpose find how many instances of element in list, delete instances list, , return key:value
pair representing element , number of instances.
so if make list , call function, should following:
>>> somelist = [1, 1, 1, 2, 3] >>> print(instances(1, somelist)) {1: 3} >>> print(somelist) [2, 3]
however, last line, instead:
>>> print(somelist) [1, 1, 1, 2, 3]
the line list(filter(candidate.__ne__, candidates))
returns correct list want, seems exists in function's scope. if modify line instead read candidates = list(filter(candidate.__ne__, candidates))
, reason candidates
being interpreted local variable inside scope of function. can't return list filter because need return key:value
pair part of program.
i find strange candidates
interpreted local variable in line, whereas above it, reference candidates
interpreted parameter of function.
can please me understand why happening? , if possible, suggest solution consistent intended purpose? thanks!
i find strange candidates interpreted local variable in line, whereas above it, reference candidates interpreted parameter of function.
python doesn't have references. has variables. foo = bar
means "make variable foo
point @ whatever bar
points at." reassigning variable re-seats pointer. doesn't let change "other" variables point given value. parameters passed using same method: make new pointer object. there no direct support three star programming
modifying list in-place done slicing syntax. this:
candidates[:] = filter(candidate.__ne__, candidates)
Comments
Post a Comment