Ternary operators in list comprehensions
5 Oct
2017
5 Oct
'17
3:40 p.m.
a = [1,2,3] [ x for x in a if x & 1] [1, 3] [ x for x in a if x & 1 else 'even'] File "<stdin>", line 1 [ x for x in a if x & 1 else 'even'] ^ SyntaxError: invalid syntax
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?
2387
Age (days ago)
2387
Last active (days ago)
4 comments
5 participants
participants (5)
-
Jason H
-
Jelle Zijlstra
-
Paul Moore
-
Rob Cliffe
-
Steven D'Aprano