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 see in output I have the first and last items which I want to not have.
I tried various things, such as to remove else statement (it's not possible), replace 0 with pass statement (it's not working either).
Is it even possible to get just needed items in list with conditionals while list comprehensions? Or it's only possible with filter function?
Needed output:
[2]
解决方案
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!"]