Skip to content Skip to sidebar Skip to footer

How To Do Nothing In Conditional Statement While Python List Comprehension?

Here is the thing: lst = [1, 2, 3] i = [x if x == 2 else 'I don't need that!' for x in lst] print(i) Output: ['I don't need this item!', 2, 'I don't need this item!'] As you can

Solution 1:

Try this:

lst = [1, 2, 3]
i = [x for x in lst if x == 2]
print(i)

Output:

[2]

You haven´t used list comprehension correctly, the if statement should come after the for loop. See list comprehensions in Python or its documentation for more information.

Before the quetions had been changed, this was the answer:

lst = [1, 2, 3]
i = [x if x == 2 else "I don't need this item!" for x in lst]
print(i)

Output:

["I don't need this item!", 2, "I don't need this item!"]

Quotation marks inside a string, explanation.


Solution 2:

You are putting the if in the wrong place. Try this:

lst = [1, 2, 3]
i = [x for x in lst if x == 2]
print(i)
# [2]

Post a Comment for "How To Do Nothing In Conditional Statement While Python List Comprehension?"