How to Apply a Function to a Python List

5/5 - (10 votes)

Problem Formulation and Solution Overview

This article will show you how to apply a function to a List in Python.

To make it more interesting, we have the following running scenario:

As a Python assignment, you have been given a List of Integers and asked to apply a function to each List element in various ways.


💬 Question: How would we write code to apply a function to a List in Python?

We can accomplish this task by one of the following options:


Preparation

These examples use functions from the math library.

Add the following code to the top of each script. This snippet will allow the code in this article to run error-free.

import math

Method 1: Use a Generator Expression

This example uses a Generator Expression. This expression performs any operations in memory first and returns an iterable object. An efficient option as upon completion, memory is cleared, and variables erased.

nums = [18, 43, 54, 65, 31, 21, 27]
nums = (math.pow(num,2) for num in nums)
print(nums)

The above code declares a List of Integers and saves it to the variable nums.

Next, a Generator Expression is called and applies the math.pow() function from Python’s built-in math library to each list element. The results save back to nums.

If output to the terminal at this point, an iterable Generator Object similar to the following displays.

<generator object at 0x000002468D9B59A0>

To turn the Generator Object into a List, run the following code.

print(list(nums))

The content of nums is as follows.

[324.0, 1849.0, 2916.0, 4225.0, 961.0, 441.0, 729.0]
Understanding Generators In Python

💡Note: The math.pow() function accepts two (2) integers as arguments: x (the value) and y (the power), and returns the value of x raised to the power of y.


Method 2: Use List Comprehension

This example uses List Comprehension to perform an operation on each List element.

nums = [18, 43, 54, 65, 31, 21, 27]
nums = [math.sqrt(num) for num in nums]
print(nums)

The above code declares a List of Integers and saves it to the variable nums.

Next, List Comprehension is called and applies the math.sqrt() function from Python’s built-in math library to each List element. The results save back to nums.

If output to the terminal, the following displays.

[4.242640687119285, 6.557438524302, 7.3484692283495345, 8.06225774829855, 5.5677643628300215, 4.58257569495584, 5.196152422706632]
Python One-Liner Trick 9 - Nested List Comprehension

💡Note: The math.sqrt() function accepts an integer as an argument and returns the square root of said argument.


Method 3: Use a Lambda and map()

This example uses Python’s lambda function combined with map() and List to apply a mathematical operation to each List element.

nums = [18, 43, 54, 65, 31, 21, 27]
nums = list(map(lambda x: math.degrees(x), nums))
print(nums)

The above code declares a List of numbers and saves it to the variable nums.

Next, List is called and passed an argument map(), which in turn passes the lambda function to apply the math.degrees() function from Python’s built-in math library to each List element. The result returns to nums.

If output to the terminal, the following displays.

[1031.324031235482, 2463.71851906254, 3093.9720937064453, 3724.225668350351, 1776.169164905552, 1203.2113697747288, 1546.9860468532227]
Let's Play Finxter - The Lambda Function in Python

💡Note: The math.degrees() function accepts an angle as an argument, converts this argument from radians to degrees and returns the result.


Method 4: Use a For Loop

This example uses a for Loop to apply a mathematical operation to each List element.

nums = [18, 43, 54, 65, 31, 21, 27]
i = 0

while i < len(nums):
    nums[i] = round(math.sqrt(nums[i]), 2)
    i += 1

print(nums)

The above code declares a List of Integers and saves it to the variable nums. Then, a counter variable, i is declared, set to 0.

Next, a while loop is instantiated and iterates through each List element, applying the math.sqrt() function, and limiting the decimal places to two (2). The results save back to the appropriate element in nums.

Upon completion of the iteration, the output is sent to the terminal.

[4.24, 6.56, 7.35, 8.06, 5.57, 4.58, 5.2]

Bonus: Calculate Commissions on each List Element

This bonus code extracts two (2) columns from a real-estate.csv file, the street and price columns and converts each into a List.

Then, the street column is converted from UPPERCASE uppercase() to Title Case by applying the title() function. Next, Sales Commissions are calculated and applied to each price element using round().

import pandas as pd

df = pd.read_csv('real-estate.csv', usecols=['street', 'price']).head(5)

street = list(df['street'])
street = [item.title() for item in street]

prices = list(df['price'])
commis = [round(p*.06,2) for p in prices]

print(street)
print(prices)

The output it as follows.

['3526 High St', '51 Omaha Ct', '2796 Branch St', '2805 Janette Way', '6001 Mcmahon Dr']
[59222, 68212, 68880, 69307, 81900]

🌟Finxter Challenge!
Convert these Lists into a Dictionary format.


Summary

This article has provided four (4) ways to apply a function to each List element to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor – Python

“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd