For an assignment I have to filter a list without using the built-in function in Python. Here's my code :
def satisfiesF(L):
result = 0
i = 0
L1 = []
while i < len(L):
s = L[i]
if f(s) == True :
result += 1
L1.append(L[i])
i += 1
L = L1
print L
return result
def f(s):
return 'a' in s
L = ['a', 'b', 'a']
print satisfiesF(L)
print L
It prints :
['a', 'a']
2
['a', 'b', 'a']
Why is the second L not the same as the first? I have searched for hours but I can't understand. It seems to me that here L is passed by reference so why doesn't the value change?
I've tried changing the line L = L1
in L = list(L1)
but the result is the same.
It's a simple mistake of the scope of local and global variables.
Inside your function satisfiesF(L)
the line
L = L1
changes the L
which is declared inside the function which you passed to the function satisfiesF()
as an argument. You could have passed L'
and tried printing L'
, it would work just fine. But print L
would give variable out of scope
error.
But when you do
print L
in the last line, it will print the L
declared just two lines above it as L = ['a', 'b', 'a']
As Himanshu points out, the scope is the issue. That is why this works, since it sets self.L
class my_test:
def __init__(self, values, check):
self.L = values
self.check = check
def run_test(self):
print self.satisfiesF()
print self.L
def f(self, s):
return self.check in s
def satisfiesF(self):
result = 0
i = 0
L1 = []
while i < len(self.L):
s = self.L[i]
if self.f(s) == True :
result += 1
L1.append(self.L[i])
i += 1
self.L = L1
print self.L
return result
x = my_test(['a', 'b', 'a'], 'a')
x.run_test()
Output is
['a', 'a']
2
['a', 'a']
L = L1
This makes L
reference to the list that L1
references. Add print(id(L))
before and after this line, you could see its id
has changed.
One way to keep L
the same id
while getting the content of L1
is to clear it first and then append:
del L[:]
L.append(L1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.