I have written some code and recently came across the need for 'nonlocal' when writing functions of functions (came across this when dealing with recursion).
For example:
def swapPairs(head):
head = None
def helper(node):
nonlocal head
...
head= nex.next
return helper(node.next)
My question is quite simple, as we call the recursion function helper(node.next)
, and loop back up to nonlocal head
- does head
take the value of None (due to nonlocal head)? Or does it retain head = nex.next
, which it was assigned to in the previous recursion call?
So I am trying to understand whether 'nonlocal head'
would cause head
to always take the value of whatever it was assigned to in the outer function, or is this not the case? And instead it is just a way to initialise head in the inner function so it only STARTS by taking the initial value as defined in the outer function.