0

EDIT: I read the linked posts in comments, but I still don't understand what I can do to my code to change it. I get why it happens now in terms of it using the same object, but which part can I change so that it won't give me an error while resetting dictOut to an empty dictionary every time it's called?


My results remember the dictOut values that were in the previous function call.

For example, calling lengthDict(["Alex", "Josh", "Fareeda", "Parul"]) gives:

--> {'Parul': 3, 'Fareeda': 3, 'Josh': 3, 'Alex': 2},

but then calling lengthDict(["Michael", "Craig", "Shane"]) after that returns:

--> {'Parul': 3, 'Fareeda': 3, 'Josh': 3, 'Alex': 2, 'Michael': 4, 'Craig': 3, 'Shane': 3}

Here is my code:

"""
Function Name: lengthDict()
Parameters: list of names (list)
Returns: dictionary mapping names to length (dict)
"""
def lengthDict(namesList, dictOut = {}, count = 0):
    if len(namesList) == 0:
        return dictOut
    consonants = 'bcdfghjklmnpqrstvwxyz'
    indX = 0
    while indX in range(len(namesList[0])):
        if namesList[0][indX].lower() in consonants:
            count += 1
        indX += 1
    dictOut[namesList[0]] = (count)
    return lengthDict(namesList[1:])
unstuck.me
  • 13
  • 4
  • Every call to `lengthDict` without an explicit second argument uses the *same* object for `dictOut`. – chepner Dec 13 '21 at 02:05
  • The short explanation is that `dictOut = {}` is only executed _once_, when the function is defined, and changes made to it are retained between calls. You do _not_ get a new copy of `dictOut` each time the function is called. See the link at the top for more details. – John Gordon Dec 13 '21 at 02:11
  • To fix this, change your function header to say `dictOut = None`, and then have the first line be `if dictOut is None:` / `dictOut = {}`. – Tim Roberts Dec 13 '21 at 02:20
  • That didn't work, it always return empty dict :( – unstuck.me Dec 13 '21 at 02:31

0 Answers0