0

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]
Quanti Monati
  • 769
  • 1
  • 11
  • 35

2 Answers2

5

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.

t3m2
  • 366
  • 1
  • 15
3

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]
norok2
  • 25,683
  • 4
  • 73
  • 99
  • Why downvoted? This is literally the same as the *edited version* of the accepted answer, except that the *edits* were not there when I wrote it... if anything, one could say my answer *inspired* the accepted one... – norok2 Aug 01 '19 at 11:22
  • This is correct. Norok2 shows here that in the case of no else, the format for list comprehensions is a bit different -- the "if" goes at the end. – geekandglitter Jun 08 '20 at 10:15