I'm new to the concept of mutability of lists in the context of for loops.
Can someone explain why the output for the below code is an empty list?
I would expect L3 = [3,4]
.
Thanks!
L1 = [1,2,3,4]
L2 = [1,2,5,6]
def no_dups(L1, L2):
L3 = []
for e in L1:
if e not in L2:
L3.append(e)
return(L3)
print(L3)
The last line print(L3)
does not even call no_dups
function. It throws an expection because L3 is not defined outside of function.
Probably you meant this:
L3 = no_dups(L1, L2)
print(L3)
In which case you do inded get the expected result.
This works:
>>> L1 = [1,2,3,4]
>>> L2 = [1,2,5,6]
>>>
>>> def no_dups(L1, L2):
... L3 = []
... for e in L1:
... if e not in L2:
... L3.append(e)
... return(L3)
...
>>> print(no_dups(L1,L2))
[3, 4]
>>>
L3
does not actually exists outside of no_dups()
, so you cannot print it or whatever
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.