1

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?

3
  • 3
    [5 if i > b else 0 for i in a] Commented Feb 18, 2022 at 15:33
  • 1
    I don't understand what that loop does. Why are you modifying the loop iteration variable? Commented Feb 18, 2022 at 15:36
  • @JohnKugelman , I was trying to make a program which list all combination of number till a specific number, and if the digit of the iteration variable is less than the digit of the given number, i want to add 0 to the iteration variable. for example if the given number is 23, and i= 4, i want i to be 004. I hope i have clear it. Commented Feb 18, 2022 at 15:54

2 Answers 2

5

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]
0
4

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]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.