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?
>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))