Subtracting non-zero elements of a list in Python

Question:

I have a list n12. I want to subtract only non-zero elements of n12 from 1. I present the current and expected output.

n12=[0,
 0.097055623870192,
 0,
 0.09668483656158318,
 0.09983696710324882,
 0.09905078620023211,
 0.09857192019636203]

n22=[1-i for i in n12]
print(n22)

The current output is

[1, 0.902944376129808, 1, 0.9033151634384168, 0.9001630328967511, 0.9009492137997679, 0.9014280798036379]

The expected output is

[0, 0.902944376129808, 0, 0.9033151634384168, 0.9001630328967511, 0.9009492137997679, 0.9014280798036379]
Asked By: isaacmodi123

||

Answers:

You can use conditions inside your loops.

n22=[1-i if i != 0 else i  for i in n12]

Check the link for more details.
Python Conditions

Answered By: zeo

You can use an if-else statement in your list comprehension:

>>> n12 = [0, 0.097055623870192, 0, 0.09668483656158318, 0.09983696710324882, 0.09905078620023211, 0.09857192019636203]
>>> n22 = [1 - x if x != 0 else 0 for x in n12]
>>> n22
[0, 0.902944376129808, 0, 0.9033151634384168, 0.9001630328967511, 0.9009492137997679, 0.9014280798036379]
Answered By: Sash Sinha

You can have conditions in a list comprehension as follows:

n22 = [0 if e == 0 else 1-e for e in n12]
Answered By: Pingu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.