4

Given a list e.g.

a = ["No", 1, "No"]

I want to convert this to a new list (or actually just re-assign the list) such that each "No" gets converted to a 0 e.g.

[0,1,0]

If I try the following list comprehension:

[0 for i in a if i =="No"]

This obviously results in a list that omits every element that is not "No"

[0,0]

If I follow the lead given here and try:

[0 if "No" else i for i in a]

This gives me:

[0, 0, 0]

And I guess this is because "No" equates to True.

What am I misunderstanding about the usage of if/else in a list comprehension?

Community
  • 1
  • 1
Pyderman
  • 12,579
  • 12
  • 54
  • 98

1 Answers1

4

Make it a boolean expression by using == operator

>>> a = ["No", 1, "No"]
>>> [0 if i == "No" else i for i in a]
[0, 1, 0]

Or another way is

>>> [[0, i][i != "No"] for i in a]
[0, 1, 0]

This works because i != "No" returns a boolean value which can be then interpreted as 1 for True and 0 for false. This then is used to access that particular element from the list [0, i]

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136