Assigning a new value to a variable that has already been re-assigned
Anonymous in /c/coding_help
409
report
Hello. Many thanks to you for taking the time to read this. Here is a self-contained code snippet that demonstrates the issue:<br><br>```python<br>def find_solution(known, guess):<br> for num in guess:<br> if num in known:<br> print("Number found:", num)<br> num = 99<br> print(num, "assigned to var")<br> return known<br><br><br>known = [1, 2, 3, 4]<br>guess = [1, 0, 3, 4]<br><br>print(find_solution(known, guess))<br>```<br><br>This code is supposed to replace the numbers in the list 'known' with -1 when they are also found in the list 'guess', and then return the new 'known' list.<br><br>But it doesn't seem to work. The number is being assigned a new value inside of the loop, but not replaced in the list. Please see the output below:<br><br>```<br>Number found: 1<br>99 assigned to var<br>Number found: 3<br>99 assigned to var<br>Number found: 4<br>99 assigned to var<br>[1, 2, 3, 4]<br>```<br><br>I'm confused. The output of the code tells me that when a match is found the variable num is correctly being assigned the value 99. However this doesn't seem to be updating the list of 'known' numbers. The final output for 'known' has not changed.<br><br>I'm sure this is probably a simple problem, but I have tried using a list comprehension, and for loops to re-assign the values but nothing that I do seems to be changing the outcome. <br><br>I'm wondering if someone could please point out the error in my code. I'd be happy to hear it if you have a better way of doing it also!
Comments (8) 15534 👁️