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.isupper() for c in text)
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 Evaluates 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']
    return val in fruits

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']
multiply_by_two = lambda num: num * 2

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

2.3.6.5. sort: Sort a List of Tuples by the First or Second Item

If you want to sort a list of tuples by the first or second item in a tuple, use the sort method. To specify which item to sort by, use the key parameter.

prices = [('apple', 3), ('orange', 1), ('grape', 3), ('banana', 2)]

# Sort by the first item
by_letter = lambda x: x[0]
prices.sort(key=by_letter)
prices
[('apple', 3), ('banana', 2), ('grape', 3), ('orange', 1)]
# Sort by the second item in reversed order
by_price = lambda x: x[1]
prices.sort(key=by_price, reverse=True)
prices
[('apple', 3), ('grape', 3), ('banana', 2), ('orange', 1)]