Ternary operators in list comprehensions

I expected [1, 'even', 3] I would expect that the if expression would be able to provide alternative values through else. The work around blows it out to: l = [] for x in a: if x&1: l.append(x) else: l.append('even') Unless there is a better way?

Putting it another way, your example doesn't make sense. How would you parenthesise it to make it clearer? [ (x for x in a if x & 1) else 'even'] You have an "else" without an "if". [ x for x in (a if x & 1 else 'even')] Using x before it has been defined, at least in this line of code. [ (x for x in a) if x & 1 else 'even'] Ditto Other variants may be possible. Whereas Jelle's correct version can be written as [(x if x & 1 else 'even') for x in a] [1, 'even', 3] Rob Cliffe On 05/10/2017 16:44, Jelle Zijlstra wrote:

On Thu, Oct 05, 2017 at 05:40:32PM +0200, Jason H wrote:
[(x if x & 1 else 'even') for x in a] The if clause in the list comprehension determines which items are included, and there is no "else" allowed. You don't want to skip any values: the list comp should have the same number of items as "a" (namely, 3) the comprehension if clause is inappropriate. Instead, you want the value in the comprehension to conditionally depend on x. By the way, this list is for suggesting improvements and new functionality to the language, not for asking for help. You should consider asking your questions on python-list or tutor mailing lists instead. -- Steve

Putting it another way, your example doesn't make sense. How would you parenthesise it to make it clearer? [ (x for x in a if x & 1) else 'even'] You have an "else" without an "if". [ x for x in (a if x & 1 else 'even')] Using x before it has been defined, at least in this line of code. [ (x for x in a) if x & 1 else 'even'] Ditto Other variants may be possible. Whereas Jelle's correct version can be written as [(x if x & 1 else 'even') for x in a] [1, 'even', 3] Rob Cliffe On 05/10/2017 16:44, Jelle Zijlstra wrote:

On Thu, Oct 05, 2017 at 05:40:32PM +0200, Jason H wrote:
[(x if x & 1 else 'even') for x in a] The if clause in the list comprehension determines which items are included, and there is no "else" allowed. You don't want to skip any values: the list comp should have the same number of items as "a" (namely, 3) the comprehension if clause is inappropriate. Instead, you want the value in the comprehension to conditionally depend on x. By the way, this list is for suggesting improvements and new functionality to the language, not for asking for help. You should consider asking your questions on python-list or tutor mailing lists instead. -- Steve
participants (5)
-
Jason H
-
Jelle Zijlstra
-
Paul Moore
-
Rob Cliffe
-
Steven D'Aprano