In the following examples,
[f(a) for a in range(10) if f(a) < 50]
{k: f(a) for k in range(10) if f(a) < 50}
Is it possible to eliminate the repeated f(a), without introducing a wrapping list/dictionary comprehension?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can avoid the repeated call to
f(a)by introducing a dummy iteration over a single-element list:or by introducing a sub-generator:
They are a bit inelegant, but they work, and are reasonably clear.
You’ll probably be interested in this long thread on the python-ideas mailing list, in which Mathias Panzenböck proposes the addition of new syntax to the language to handle this case more elegantly. Generally, the response from the Python developers was that the problem isn’t severe enough to warrant the additional complexity.