0

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
3
  • 1
    for i in precipitation gives you the actual items in the list, not their respective indices. The simplest fix to your code is for i in range(len(precipitation)):, which will have i take the value of the indices. Simpler solutions also exist, but this one most closely matches what you have now. Commented Oct 11, 2020 at 5:42
  • 2
    [0 if x!="Sun" else 1 for x in precipitation] Commented Oct 11, 2020 at 5:45
  • Shivam, can you show your new code, that gives you all 1s? And as @TomRon points out, there are simpler solutions. Commented Oct 11, 2020 at 5:54

4 Answers 4

3

You can do it using list comprehension:

precipitation = [0 if x == 'Sun' else 1 for x in precipitation]
Sign up to request clarification or add additional context in comments.

2 Comments

I guess questioner wants 0 for 'Sun'.
@JenilDave Changed it. Thank you!
1

An elaboration of @Gabip's answer, using the fact that the boolean values are numerically represented as 0 and 1:

[int(x=='Sun') for x in precipitation]

Comments

0

Try this...

precipitation = ["Sun", "Rain", "Rain", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Rain", "Rain", "Rain", "Rain"]

for i in range(len(precipitation)):  
  if precipitation[i] == "Sun":
    precipitation[i] = 0
  else:
    precipitation[i] = 1
         
print(precipitation)

Comments

0

Adding to answers already present, using map()

list(map(lambda x: 0 if x=='Sun' else 1,a))

You can try this to avoid loops and list comprehensions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.