While studying Python, I was addicted to the list comprehension notation for an hour. I think it's because I thought Python functions were passed by reference. (Although I may have misunderstood "pass by reference")
If you compare the execution results, you can see what happened, I'm sure.
I created the opening function findDiff ()
to try to find out what's added and what's removed.
But when I returned from the function, the elements of the list disappeared (looked like).
def findDiff(oldList, newList, adds, dels):
adds = [x for x in newList if oldList.count(x) < 1]
dels = [x for x in oldList if newList.count(x) < 1]
oldList = [1,2,3,5,6,7,8,9]
newList = [1,2,4,5,6,7,8,10]
adds = []
dels = []
print(adds)
print(dels)
findDiff(oldList, newList, adds, dels)
print(adds)
print(dels)
#>>> []
#>>> []
#>>> []
#>>> []
Only the function findDiff ()
at the beginning is modified.
def findDiff(oldList, newList, adds, dels):
for x in newList:
if oldList.count(x) < 1:
adds.append(x)
for x in oldList:
if newList.count(x) < 1:
dels.append(x)
oldList = [1,2,3,5,6,7,8,9]
newList = [1,2,4,5,6,7,8,10]
adds = []
dels = []
print(adds)
print(dels)
findDiff(oldList, newList, adds, dels)
print(adds)
print(dels)
#>>> []
#>>> []
#>>> [4, 10]
#>>> [3, 9]
When I looked it up after writing the article, I already had the wisdom of my predecessors. .. ..
Recommended Posts