Python all() Function

Python all() function returns True if all the elements of an iterable are True. If any element in the iterable is False, all() returns False.

all() can be thought of as logical AND operation on elements on iterable.

  • All values are True, all() returns True.
  • All values are False, all() returns False.
  • One value is True (others are False), all() returns False.
  • One value is False (others are True), all() returns False.
  • Empty Iterable, all() returns True.

Syntax

The syntax of all() method is :

return_val = all( iterable )

Function parameter and return value

  • The all() method takes a single required argument of iterable type, for example a list, set, tuple or dictionary.
  • The return value is of bool type whose value is either True or False.

Python all() Function Example

all() Function with Tuple

Python program to check if all the items in a tuple are True. In given tuple, the value 0 is considered as False.

mytuple = (0, 1, False)
print(all(mytuple))		#False

mytuple = (1, 2, 3)
print(all(mytuple))		#True

mytuple = (1, 2, True)
print(all(mytuple))		#True

mytuple = ()
print(all(mytuple))		#True

Program output.

False
True
True
True

all() Function with List

Python program to check if all the items in a list are True. List acts very much like tuple in case of all() function.

myList = [0, 1, False]
print(all(myList))

myList = [1, 2, 3]
print(all(myList))

myList = [1, 2, True]
print(all(myList))

myList = []
print(all(myList))

Program output.

False
True
True
True

all() Function with Dictionary

Python program to check if all the items in a dictionary are True. In the given dictionary, the first instance is having a single False value. The second instance has two values, both are True.

d = {0: 'False'}
print(all(d))

d = {1: 'True', 2: 'True'}
print(all(d))

Program output.

False
True

all() Function with String

Python program to use all() to check is string is empty or not. For an empty string, all() wil return False, else it will return True.

s = ''
print(all(s))

s = '  '
print(all(s))

s = 'abc'
print(all(s))

s = '123'
print(all(s))

Program output.

True
True
True
True

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.