2.3.5. Apply Functions to Elements in a List#

2.3.5.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.5.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.5.3. 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]

2.3.5.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]

2.3.5.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)]

2.3.5.6. Use any and List Comprehension Instead of an If-Else Statement#

If you want to check whether a statement is True for one or more items in a list, using any and list comprehension is simpler than using a for-loop and an if-else statement.

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.')
True
def check_mention_fruit_2(text: str):
    
    return any(fruit in text for fruit in FRUITS)

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