Reputation: 1326
I'm wondering if there is a pythonic way of achieving an if-statement in "list-comprehension style". If it exists, the solution is probably an easy one, but I have no clue where to look this up (or how this is called).
mylist= ["foo", "bar", "baz"]
x = "bar"
mc = MyClass(param1 =foo, param2=bar, is_expected=[x if x in mylist]
Depending on the value x
holds, the value of the parameter is_expected
should been set (True
if it's in the list, otherwiese False
) and passed to the constructor.
Upvotes: 0
Views: 49
Reputation: 2853
x in mylist
would return you a bool. If x was in that list, result would be true and if not, result would be false
so you can use mc = MyClass(param1 =foo, param2=bar, is_expected=x in mylist)
Upvotes: 0
Reputation: 1554
Just use
mc = MyClass(param1 =foo, param2=bar, is_expected = (x in mylist))
Upvotes: 2