>>> a = [1,2,3] >>> [x if x & 1 else 'even' for x in a] [1, 'even', 3]
You're mixing the if clause of the list comprehension up with a ternary expresssion. There's no "else" in the list comprehension if clause. Paul On 5 October 2017 at 16:40, Jason H <jh...@gmx.com> wrote: >>>> 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? > _______________________________________________ > Python-ideas mailing list > Python-ideas@python.org > https://mail.python.org/mailman/listinfo/python-ideas > Code of Conduct: http://python.org/psf/codeofconduct/ _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/