Reputation: 55
The issue I am having is that it should be impossible not break out of the while loop, AKA "matched_index" will always be defined, yet my IDE is throwing an "may be referenced before assignment" error. What is the Pythonic way to code this? The closest I found was this post, but I'm not sure how to code what kindall is suggesting.
Here is my code:
another_list = [0] * len(my_list)
if X in my_list:
i = 0
while i < len(my_list):
if X == my_list[i]:
matched_index = i
break
i += 1
another_list[matched_index] = 0.2
Upvotes: 0
Views: 416
Reputation: 106430
Just initialize matched_index
, or move your assignment statement into the loop (so that you're not using another temporary variable to hold it).
While it might be true that, from a logical perspective, the code won't run into a scenario where len(my_list) == 0
, the lexer can't guarantee it.
Upvotes: 3