Python all() Function With Examples

In this article we are going to talk about the Python all() function with examples.

Getting Started

all() function is one of Built-in functions in Python that returns True if all elements of iterable, passed as parameter, are True or if they are empty.

Syntax of all() Function

The syntax of all() function in Python is shown below –

all(iterable)

all() function accepts an iterable as parameter.

If we pass any value which is not iterable, all() function throws a TypeError as shown below.

print(all(2))

Here, we get TypeError as output because 2 is an integer that is not an iterable.

It will be same for any parameter, passed to all() function, which is not an iterable.

Parameters of all() Function

As shown above in the syntax, all() function takes only a single parameter – one iterable.

Iterable can be an object of –

Return type of all() Function

In Python, all() function returns a boolean value (i.e. True or False).

all() function returns

  • True: If either all elements of iterable are True or iterable is empty
  • False: In any other case.

Examples of all() Function with Output

Till now, we have discussed what is all() function, it’s syntax, it’s return type etc. Now, we will go through some examples of all() function in python.

Example 1

In this example, we will use all() function with string in python

my_variable = "mother"
print(all(my_variable))

Output:

True

Here,

  • my_variable is string whose all elements are True.
  • So, output is True

Example 2

Now, we will use all() function with list in python

my_list = [ "mother", "father" ]
print(all(my_list))

Output:

True

Here,

  • Variable my_list is an iterable whose all elements are True.
  • So, output is True

Example 3

Now, we will use all() function with tuple in python

my_tuple = (1, 2, 3, 4, 5, 7, 8, 9, 10)
print(all(my_tuple))

Output:

True

Here,

  • Variable my_tuple is an iterable whose all elements are True.
  • Hence, output is True.

Example 4

Now, we will use all() function with set in python

my_set = {1, 2, 3, 4, 5}
print(all(my_set))

Output:

True

Here,

  • Variable my_set is an iterable whose all elements are non-zero i.e. True.
  • Hence, output is True.

Example 5

another_set = { }
print(all(another_set))

Output:

True

Here,

  • Variable another_set is an empty set.
  • Hence, output is True.

That’s how we can use python all() function with examples.

Reference – official doc

Leave a Reply