Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this function not work for this specific instance

So i have created this function which takes two arguments (a function with one argument and a list). its purpose is to iterate through the list and return true if every instance of the function is True (else return False). So for my attempt i have this:

def all_iter(func, ls):
    i = 0
    c = True    
    for i in ls:
     if func(ls[i]) == False:
        c = False
        break
    return c   

now these are the three examples i have used to see whether it runs properly and they should return :

>>>all_iter(lambda x: x >= 0, [1, 2, 3, 0, 4])
True
>>> all_iter(lambda x: x >= 0, [1, 2, -3, 0, 4])
False
>>> all_iter(lambda x: x % 2 == 0, [100, 10, 2022, 12])
True

Now for the first two examples the result i get when i run this are correct but for the third one i get:
in all_iter
if func(ls[i]) == False:
IndexError: list index out of range
. Can someone provide some help?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This loop:

    for i in ls:
     if func(ls[i]) == False:

will only work if every element i of ls is also a valid index of ls. In your first few inputs, all of the elements happened to be smaller than the length of the list, but you hit an IndexError on the last case because the values were much larger.

What you might have meant to do is:

   for i in ls:
       if not func(i):

Note that there is a built-in function all that simplifies this entire thing:

def all_iter(func, ls):
    return all(func(i) for i in ls)

or equivalently with map():

def all_iter(func, ls):
    return all(map(func, ls))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading