Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Ternary Conditional Operator in a List-Comprehension

I am trying to implement a ternary conditional operator in a list-comprehension. I have written it like this:

lst.append(dict2obj(item)) if type(item) is not in ['int'] else lst.append(item) for item in v

Where lst is empty list and v is another list with various elements. Editor is showing it syntactically incorrect. What am I doing wrong?

like image 660
gliese581g Avatar asked Feb 14 '23 02:02

gliese581g


1 Answers

  • If you mean to write list comprehension you missed [, ]:
  • There is no is not in operator. Use not in.
  • type function does not return string. Why not use isinstance(item, int)?

[lst.append(dict2obj(item)) if not isinstance(item, int) else lst.append(item)
 for item in v]

Use simple for loop if possible. It's more readable.

for item in v:
    if not isinstance(item, int)
        lst.append(dict2obj(item))
    else:
        lst.append(item)
like image 115
falsetru Avatar answered Feb 20 '23 11:02

falsetru