0

I have a list of strings and want to loop over the list and make the value in the list 0 if it is a specific string. Below is the code I am attempting but it is not working:

variable1 = ['None', 'One', 'Two', 'Three', 'None']   
variable2 = [0 if v is 'None' else v for v in variable1]

The result should be: [0, 'One', 'Two', 'Three', 0] but it is not changing the None strings.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Zorpho
  • 182
  • 1
  • 14

1 Answers1

5

Avoid is, since it requires the strings to be the same object. Use == so two distinct string objects can still compare equal.

variable2 = [0 if v == 'None' else v for v in variable1]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578