0
for i in range(l):
   q = input()
   if(q not in array_num):
       print("NOT PRESENT")
   else:
       print(array_num.count(q))

i wrote below, but dont know where to use q = input()

[print("NOT PRESENT") if q not in array_num else print(array_num.count(q)) for i in range(l)]
Artog
  • 1,132
  • 1
  • 13
  • 25
  • *Why* do you need this to be with a list comprehension? – Artog Nov 04 '19 at 07:15
  • Using neat features is great and all, but the first code bit is readable, understandable, maintainable and clear. The other bit, not so much. – Artog Nov 04 '19 at 07:18
  • 2
    A list comprehension returns a `list`. Here you are printing out results on each iteration, so no point using it here. – Shijith Nov 04 '19 at 07:20
  • I am just trying out if there is a situation like this can we write python comprehension? – ROSHAN PANDEY Nov 04 '19 at 07:23
  • 1
    list comprehension doesn't allow to assing value to variable - you would have to use `for q in [input()]` and then you can construct list comprehension - but it would create unreadable code. – furas Nov 04 '19 at 07:25
  • 1
    While you can, I dont think it is good idea to use `input` within a list comprehension – shahkalpesh Nov 04 '19 at 07:27

1 Answers1

2

Using list comprehensions for its side-effects is best avoided. See Is it Pythonic to use list comprehensions for just side effects? and Printing using list comprehension. That said, just for fun's sake, with Python3.8's walrus operator, you can accomplish this with

[print("NOT PRESENT") if (q:=input()) not in array_num else print(array_num.count(q)) for i in range(l)]

where the expression q:=input() will cause the return value of input() to be assigned to q and the value of the expression itself would become that of the new value of q.

J...S
  • 5,079
  • 1
  • 20
  • 35