Skip to content

How to Apply a Function to Every Element in a List in Python

Learn the three best methods for transforming lists in Python: list comprehensions, map(), and NumPy, including performance comparisons and use cases.

Transforming a list of data, known as mapping, is a fundamental operation in programming. Whether you need to square numbers, uppercase strings, or parse objects, Python offers several effective approaches.

This guide covers the three main techniques and when to use each one.

Using List Comprehensions

For most cases, list comprehensions are the recommended approach. They are readable, fast, and considered the most Pythonic solution.

prices = [10.00, 20.00, 30.00]

taxed_prices = [price * 1.10 for price in prices]

print(taxed_prices)

Output:

[11.0, 22.0, 33.0]

Applying Custom Functions

def format_currency(amount: float) -> str:
    return f"${amount:.2f}"

prices = [10.00, 20.00, 30.00]
formatted = [format_currency(price) for price in prices]

print(formatted)

Output:

['$10.00', '$20.00', '$30.00']

Filtering While Transforming

List comprehensions can filter and transform in a single expression:

numbers = range(10)

even_squares = [x ** 2 for x in numbers if x % 2 == 0]

print(even_squares)

Output:

[0, 4, 16, 36, 64]

Using the map() Function

The map() function comes from functional programming. It applies a function to every item in an iterable.

names = ["alice", "bob", "charlie"]

upper_names = list(map(str.upper, names))

print(upper_names)

Output:

['ALICE', 'BOB', 'CHARLIE']

Using map() with Lambda Functions

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

squared = list(map(lambda x: x ** 2, numbers))

print(squared)

Output:

[1, 4, 9, 16, 25]

Mapping Multiple Iterables

The map() function can apply a function to corresponding elements from multiple iterables:

prices = [100, 200, 300]
discounts = [0.1, 0.2, 0.15]

final_prices = list(map(lambda p, d: p * (1 - d), prices, discounts))

print(final_prices)

Output:

[90.0, 160.0, 255.0]

Using NumPy for Numerical Data

When working with large numerical datasets, standard Python lists become slow. NumPy arrays support vectorization, which applies operations to entire arrays at once using optimized C code.

import numpy as np

numbers = np.array([1, 2, 3, 4, 5])

squared = numbers ** 2
doubled = numbers * 2
roots = np.sqrt(numbers)

print(f"Squared: {squared}")
print(f"Doubled: {doubled}")
print(f"Roots: {roots}")

Output:

Squared: [ 1  4  9 16 25]
Doubled: [ 2  4  6  8 10]
Roots: [1.         1.41421356 1.73205081 2.         2.23606798]

Applying Custom Functions with NumPy

Use np.vectorize() to apply custom Python functions to arrays:

import numpy as np

def classify_score(score):
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    return 'F'

scores = np.array([95, 82, 67, 73, 88])
classify = np.vectorize(classify_score)

grades = classify(scores)
print(grades)

Output:

['A' 'B' 'F' 'C' 'B']

Choosing the Right Method

Method Syntax Best For
List Comprehension [f(x) for x in items] General use. Best readability and flexibility.
map() map(func, items) When you have an existing function to apply.
NumPy array * 2 Large numerical datasets. Essential for data science.

Performance Comparison

For small to medium lists, the performance difference is negligible. For large datasets:

import time
import numpy as np

data = list(range(1_000_000))
np_data = np.array(data)

start = time.time()
result = [x * 2 for x in data]
print(f"List comprehension: {time.time() - start:.4f}s")

start = time.time()
result = list(map(lambda x: x * 2, data))
print(f"map(): {time.time() - start:.4f}s")

start = time.time()
result = np_data * 2
print(f"NumPy: {time.time() - start:.4f}s")

Typical Output:

List comprehension: 0.0272s
map(): 0.1681s
NumPy: 0.0078s

Summary

  • Use list comprehensions as your default choice for readability and flexibility.
  • Use map() when applying an existing function, especially with multiple iterables.
  • Use NumPy for numerical computations on large datasets where performance matters.
Navigation