2.3.5. Apply Functions to Elements in a List# 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 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 filter: Get the Elements of an Iterable that a Function Evaluates True#

If you want to get only the elements of an iterable that satisfy the given condition, use filter.

nums = [1, 2, 3, 4, 5]

# Get even numbers
list(filter(lambda num: num % 2 == 0, nums))
[2, 4] map method: Apply a Function to Each Item of an Iterable#

If you want to apply a function to each element of an iterable, use map.

nums = [1, 2, 3, 4, 5]

# Multiply every number by 2
list(map(lambda num: num * 2, nums))
[2, 4, 6, 8, 10] sort: Sort a List of Tuples by the First or Second Item#

To sort a list of tuples, use the sort() method and pass in the key parameter to indicate which item to sort by.

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

# Sort by the first item
by_letter = lambda x: x[0]
[('banana', 2), ('grape', 3), ('orange', 1)]
# Sort by the second item
by_price = lambda x: x[1]
[('orange', 1), ('banana', 2), ('grape', 3)] Simplify List Condition Evaluation with any and List Comprehensions#

When checking if a condition is true for any list element in Python, use any with a list comprehension instead of a for loop and if-else statements for more readable code.

FRUITS = ['apple', 'orange', 'grape']

def check_mention_fruit_1(text: str):
    for fruit in FRUITS:
        if fruit in text:
            return True 

check_mention_fruit_1('I got an apple.')
def check_mention_fruit_2(text: str):
    return any(fruit in text for fruit in FRUITS)

check_mention_fruit_2('I got an apple.')
sum([1, 2, 3], start=10)