List Functions in Python

The all and any functions

all() and any() – take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise).

Example:

nums = [55, 44, 33, 22, 11]
if all([i > 5 for i in nums]):
	print("All larger than 5")
if any([i % 2 == 0 for i in nums]):
	print("At least one is even")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
All larger than 5
At least one is even
ddn_ro@linux:~/Desktop$

The enumerate function

enumerate() – can be used to iterate through the values and indices of a list simultaneously.

Example:

nums = [55, 44, 33, 22, 11]
for v in enumerate(nums):
	print(v)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
ddn_ro@linux:~/Desktop$

Leave a Reply