Search code examples
pythonpython-3.xlistfor-looplist-comprehension

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?


Solution

  • Your attempt:

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

    Is close, you just want to give 5 not i like so:

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

    Test code:

    a = [1,2,3,4,5,6,7,8,9,10]
    b = 3
    output = [5 if i>b else 0 for i in a]
    print(output)
    

    Output:

    [0, 0, 0, 5, 5, 5, 5, 5, 5, 5]
    

    This works because the item before the if is given when the statement evaluates to True and the value after the else is given otherwise. So:

    output = NumberIfTrue if LogicStatement else NumberIfFalse
    

    is equivalent to :

    if LogicStatement:
        output = NumberIfTrue
    else:
        output = NumberIfFalse
    

    In your case:

    LogicStatement = i>b
    NumberIfTrue = 5
    NumberIfFalse = 0
    

    Thus you need (as shown above):

    5 if i>b else 0
    

    Then you want to apply this to every item in a list which adds:

    for i in a
    

    like so:

    5 if i>b else 0 for i in a
    

    This is now a generator, since you want a list, you have to surround the generator with [] brackets so that it "generates" the list with the values you want. So just:

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

    Then to get the final solution we just assign the result to output so it can be used again:

    output = [5 if i>b else 0 for i in a]