Jeopardy challenge project, use of all() function

Hi guys,

Been working through the jeopardy challenge project (

Looking through the solution, the challenge suggests using one of the built in python functions (all()), however this is the first time ive seen this and can’t get my head around how it works in the example.

So from what I gather, all() is the equivalent of this:

def all(iterable): for element in iterable: if not element: return False return True
In the code example it is utilised in this way:

# Filtering a dataset by a list of words
def filter_data(data, words):
  # Lowercases all words in the list of words as well as the questions. Returns true is all of the words in the list appear in the question.
  filter = lambda x: all(word.lower() in x.lower() for word in words)
  # Applies the labmda function to the Question column and returns the rows where the function returned True
  return data.loc[data["Question"].apply(filter)]

Im very confused about how this function is accepting a for loop as an argument as well as what the temp variable “word” actually relates to.

Has anyone come across this, or can anyone share a half decent explanation of this function and its usage. Just from the example, it seems very useful but is a couple of levels above my current python understanding.

1 Like

A little experimentation in the terminal goes a long way!

>>> help(all)
all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

>>> list_of_bools = [True, True, True]
>>> list_of_bools2 = [False, True, True]
>>> all(list_of_bools)
>>> all(list_of_bools2)

Hope this gives you an idea!!

It doesn’t take a for-loop as much as it takes an iterable (like a list).
In for word in words, word is just the iterating item of the list.
In a for-loop it would look like:

for word in words:
   word.lower() in x.lower()

Which would return bools of whether the lower cased iterating item is in the reference point you’re checking it against (x).

Your lambda function filter would also take in an iterable afterward (this is the x you’re checking against as a reference.

So to summarize:

You have two iterables (in this case words, and data["Question"]). You are running a filter function on them. The method this function uses is all() which will either return True or False. The all() will be applied to compare all the items against each other.

Going along with the earlier terminal demo:

>>> list_of_bools = [True, True, True]
>>> list_of_bools2 = [False, True, True]
>>> list_of_bools3 = [False, False, False]
filter = lambda x:all(i in x for i in list_of_bools)
>>> filter
<function <lambda> at 0x7fdf8cd18d40>
>>> filter(list_of_bools2)
>>> filter(list_of_bools3)

At this point you may have some questions: (why does it return True for bools2??) but I’ll leave that for experimentation… as it is half the fun.