I create an empty list at the top level. Then, inside a function, I populate that list with single-char strings, and remove duplicates from the list.
knownBad = []
def main():
badTemp = input("Enter all letters not in the word: ")
for i in badTemp:
knownBad.append(i)
knownBad = list(dict.fromkeys(knownBad))#removes duplicates
print(knownBad)
main()
When I do this, I get the Traceback error:
Traceback (most recent call last):
File "c:\Users\mvery\OneDrive - Diocese of Greensburg Schools\Desktop\Python\demo.py", line 10, in <module>
main()
File "c:\Users\mvery\OneDrive - Diocese of Greensburg Schools\Desktop\Python\demo.py", line 6, in main
knownBad.append(i)
UnboundLocalError: local variable 'knownBad' referenced before assignment
This seems very strange, considering that the 'knownBad' variable is actually a list, which is mutable structures. The list 'knownBad' isn't really being 'assigned' in the function, as it's been created at the top level.
Is there something stupid I'm missing? Is line 7 just a very wrong way of going about stripping duplicates from a list? Could it maybe have something to do with creating a dictionary from the list, and then using that dictionary's fromkeys() method to alter the list?
I've discovered that the line that checks the list items for duplicates (line 7) seems to be causing the problem. When it's commented out, the error doesn't appear, and the program resolves as expected (of course without removing duplicates). I see how line 7 is a type of assignment to the 'knownBad' list, but the list still already exists. It isn't like the list is being created at line 7.
I found two solutions to the problem here, but I don't understand why the problem is occurring in the first place. This seems to fly in the face of the mutability of lists.
Thanks for any help!