Apply a Custom Function to a List in Python

  • Post category:List

We can apply a function to each element of a list in Python using a for loop or a list comprehension. Here are two examples:

Example 1:

def square(x):
    return x ** 2

numbers = [2, 3, 4, 5]
squares = []
for number in numbers:
    squares.append(square(number))
print(squares)

Output:

4

Example 2:

def capitalize(word):
    return word.capitalize()

words = ['apple', 'banana', 'orange', 'kiwi']
capitalized_words = [capitalize(word) for word in words]
print(capitalized_words)

Output:

[‘Apple’, ‘Banana’, ‘Orange’, ‘Kiwi’]