mercredi 26 septembre 2018

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:
        print("Minimum of the given function is:", i)

which gives me the correct answer 2.

Now I should translate that as a list comprehension, but I do not know where to put the if statement:

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

Of course, as an output I get a true/false list, with the index 2 being the correct true. But How do I include the if in my list comprehension?

Aucun commentaire:

Enregistrer un commentaire