In the following list, I want to replace "Sun" with a 0 and "Rain" with a 1. How can I do that?
precipitation = ["Sun", "Rain", "Rain", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Rain", "Rain", "Rain", "Rain"]
for i in precipitation:
if precipitation[i] == "Sun":
precipitation[i] = 0
else:
precipitation[i] = 1
for i in precipitationgives you the actual items in the list, not their respective indices. The simplest fix to your code isfor i in range(len(precipitation)):, which will haveitake the value of the indices. Simpler solutions also exist, but this one most closely matches what you have now.