2.3.6. Apply Functions to Elements in a List

2.3.6.1. any: Check if Any Element of an Iterable is True

If you want to check if any element of an iterable is True, use any. In the code below, I use any to find if any element in the text is in uppercase.

text = "abcdE"
any(c for c in text if c.isupper())
True

2.3.6.2. all: Check if All Elements of an Interable Are Strings

If you want to check if all elements of an iterable are strings, use all and isinstance.

l = ['a', 'b', 1, 2]

all(isinstance(item, str) for item in l)
False

2.3.6.3. filter: Get the Elements of an Iterable that a Function Returns True

If you want to get the elements of an iterable that a function returns true, use filter.

In the code below, I use the filter method to get items that are fruits.

def get_fruit(val: str):
    fruits = ['apple', 'orange', 'grape']
    if val in fruits:
        return True 
    else:
        return False 

items = ['chair', 'apple', 'water', 'table', 'orange']
fruits = filter(get_fruit, items)
print(list(fruits))
['apple', 'orange']

2.3.6.4. map method: Apply a Function to Each Item of an Iterable

If you want to apply the given function to each item of a given iterable, use map.

nums = [1, 2, 3]
list(map(str, nums))
['1', '2', '3']
def multiply_by_two(num: float):
    return num * 2


list(map(multiply_by_two, nums))
[2, 4, 6]