List comprehension with if-else
Carl Meyer
carl at oddbird.net
Wed Oct 28 12:36:06 EDT 2015
Hi Larry,
On 10/28/2015 10:25 AM, Larry Martell wrote:
> I'm trying to do a list comprehension with an if and that requires an
> else, but in the else case I do not want anything added to the list.
>
> For example, if I do this:
>
> white_list = [l.control_hub.serial_number if l.wblist ==
> wblist_enum['WHITE'] else None for l in wblist]
>
> I end up with None in my list for the else cases. Is there a way I can
> do this so for the else cases nothing is added to the list?
You're not really using the if clause of the list comprehension here,
you're just using a ternary if-else in the result expression. List
comprehension if clauses go at the end, and don't require an else:
[l.foo for l in wblist if l.bar == "baz"]
Carl
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20151028/cbd33c4e/attachment.sig>
More information about the Python-list
mailing list