Skip to content Skip to sidebar Skip to footer

Where To Put The If-condition Inside A List Comprehension?

I was given the function: x**2 - 4*x + 6 and the task was to find the minimum integer values x between 0 and 10. I had to use a for loop: for i in range(11): if 2*i-4==0:

Solution 1:

You are finding a single value, not a list of values. A list comprehension makes little sense here.

Your error is in putting your test in the value expression section of the list comprehension. That's not a filter, that's the part where you build the new list values from the (filtered) elements from the loop.

Put an ifafter the for loop part:

[i for i in range(11) if 2 * i - 4 == 0]

This builds a list with just one element, the i value for which the value is true:

>>>[i for i inrange(11) if2 * i - 4 == 0]
[2]

If you must do this in a single line, use a generator expression, then use the next() function to get the first result from that:

gen = (i for i in range(11) if 2 * i - 4 == 0)
result = next(gen)

This will get you the minimal value for i even if there were to be multiple possible values for i where the if test would be true.

A generator is lazily evaluated; the loop stops the moment i reaches a value where the if test is true, and that one value is produced. next() only returns that first value, so no more iteration takes place. It's as if you used break in a for loop (except you can continue the loop later).

Note that this can raise a StopIteration exception if the generator doesn't produce any values. You can tell next() to return a default value in that case; a second argument to next() is returned if StopIteration would be raised otherwise:

result = next(gen, None)

You can combine the generator expression in the next() call; if a generator expression is the only argument you can omit the (...) parenthesis of the generator expression, otherwise include them so that it can be distinguished from other arguments:

result = next((i for i inrange(11) if2 * i - 4 == 0), None)

Solution 2:

if you really want to use a comprehension and not a classic loop here, since there is only one result, you could pass a generator to next with a default value just in case it doesn't find anything:

next((i for i inrange(11) if2*i-4==0),None)

Post a Comment for "Where To Put The If-condition Inside A List Comprehension?"