Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using python command if a condition is true in list comprehension?

I wanted to convert the below code into list comprehension.

for i in list:
    if i>b:
        i=5
    else:
        i=0

I tried to use [i if i>b 5 else 0 for i in a] but it resulted in a syntax error. I have also tried [i for i in a if i>b 5 else 0] but that too resulted in a syntax error.

Any solutions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your version

  [i if i>b 5 else 0 for i in list]

The syntax error is right after the i>b.
You have the "true value" there, it is in the wrong place.
Riffing on your original code

for i in list:
    if i>b: #condition
        i=5 #true action
    else:
        i=0 #false action

The real answer is

[5 if i > b else 0 for i in list]

the pseudo code version

[<true action> if <condition> else <false action> for i in list]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading