5

Sorry if being so simple; as I searched elsewhere but nobody had pointed out to this specific problem. I'd like to learn python in a way that makes my code compact! So, to this end, I'm trying to make use of one-line (i.e., short) loops instead of multi-line loops, specifically, for loops. The problem arises when I try to use one-line if and else inside the one-line loops. It just doesn't seem to be working. Consider the following, for example:

numbers = ... # an arbitrary array of integer numbers

over_30 = [number if number > 30 for number in numbers]

This is problematic since one-line if does need else following it. Even though, when I add else to the above script (after if): over_30 = [number if number > 30 else continue for number in numbers], it turns into just another pythonic error.

I know that the problem is actually with one-line if and else, because python needs to identify a value that should be assigned to the lefthand operator. But, is there a work-around for the specific use-case of this schema as above?

0

2 Answers 2

12

They are different syntaxes. The one you are looking for is:

over_30 = [number for number in numbers if number > 30]

This is a conditional list comprehension. The else clause is actually a non-conditional list comprehension, combined with a ternary expression:

over_30 = [number if number > 30 else 0 for number in numbers]

Here you are computing the ternary expression (number if number > 30 else 0) for each number in the numbers iterable.

Sign up to request clarification or add additional context in comments.

Comments

2

continue won't work since this is ternary expression, in which you need to return something.

val1 if condition else val2

You can try this way:

over_30 = [number for number in numbers if number > 30]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.