Call Function on All Elements in a List Using List Comprehension in Python

In Python, you can apply a function to all elements of a list using list comprehension. This allows you to transform a list efficiently in a single line of code without using loops explicitly.

The syntax is:

[function(x) for x in my_list]

where each element in the list is processed by the function.


Example

1. Applying a Function to Square Each Number in a List

We will create a function that squares a number and use list comprehension to apply this function to each element in the list.

</>
Copy
# Function to square a number
def square(num):
    return num ** 2

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Using list comprehension to apply square() to each element
squared_numbers = [square(n) for n in numbers]

# Printing the transformed list
print("Original List:", numbers)
print("Squared List:", squared_numbers)

Explanation

Here’s how we apply the function to all elements using list comprehension:

  1. We define a function square(num) that returns the square of a given number.
  2. We create a list of numbers numbers = [1, 2, 3, 4, 5].
  3. We use list comprehension [square(n) for n in numbers] to apply the square() function to each element of numbers.
  4. The result is stored in squared_numbers, which contains the squared values of all elements.
  5. Finally, we print the original and transformed lists.

Output:

Original List: [1, 2, 3, 4, 5]
Squared List: [1, 4, 9, 16, 25]

The output shows that each number in the original list has been squared using the function and stored in the new list.