09-13-2022, 07:21 PM
How to Apply a Function to a List
5/5 – (2 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 https://blog.finxter.com/python-lists/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 https://blog.finxter.com/python-lists/List in Python?
We can accomplish this task by one of the following options:
Preparation
These examples use functions from the library.
Add the following code to the top of each script. This snippet will allow the code in this article to run error-free.
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.
The above code declares a List of Integers and saves it to the variable.
Next, a Generator Expression is called and applies the function from Python’s built-in library to each list element. The results save back to .
If output to the terminal at this point, an iterable Generator Object similar to the following displays.
To turn the Generator Object into a https://blog.finxter.com/python-lists/, run the following code.
The content ofis as follows.
[324.0, 1849.0, 2916.0, 4225.0, 961.0, 441.0, 729.0]
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2Ls0b1gjz2A%2Fhqdefault.jpg)
Note: The function accepts two (2) integers as arguments: (the value) and (the power), and returns the value of raised to the power of .
Method 2: Use List Comprehension
This example uses List Comprehension to perform an operation on each List element.
The above code declares a List of Integers and saves it to the variable.
Next, List Comprehension is called and applies thehttps://blog.finxter.com/a-guide-to-pyth...-function/ function from Python’s built-in library to each https://blog.finxter.com/python-lists/List element. The results save back to .
If output to the terminal, the following displays.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaBC0VhpXkOQ%2Fhqdefault.jpg)
Note: The 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 function combined with and https://blog.finxter.com/python-lists/List to apply a mathematical operation to each List element.
The above code declares a https://blog.finxter.com/python-lists/List of numbers and saves it to the variable.
Next, List is called and passed an argument, which in turn passes the function to apply the function from Python’s built-in library to each https://blog.finxter.com/python-lists/i element. The result returns to .
If output to the terminal, the following displays.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkBg4n52XoUQ%2Fhqdefault.jpg)
: The 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 Loop to apply a mathematical operation to each List element.
The above code declares a https://blog.finxter.com/python-lists/List of Integers and saves it to the variable. Then, a counter variable, is declared, set to 0.
Next, a loop is instantiated and iterates through each List element, applying the https://blog.finxter.com/a-guide-to-pyth...-function/ function, and limiting the decimal places to two (2). The results save back to the appropriate element in .
Upon completion of the iteration, the output is sent to the terminal.
Bonus: Calculate Commissions on each List Element
This bonus code extracts two (2) columns from a file, the street and price columns and converts each into a List.
Then, the street column is converted from UPPERCASE to Title Case by applying the https://blog.finxter.com/python-string-title/ function. Next, Sales Commissions are calculated and applied to each price element using .
The output it as follows.
Finxter Challenge!
Convert these Lists into a Dictionary format.
Summary
This article has provided four (4) ways to apply a function to each element to select the best fit for your coding requirements.
Good Luck & Happy Coding!
Programming Humor – Python
[i]“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.” — xkcd[/i]
5/5 – (2 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 https://blog.finxter.com/python-lists/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 https://blog.finxter.com/python-lists/List in Python?We can accomplish this task by one of the following options:
- Method 1: Use a Generator Expression
- Method 2: Use List Comprehension
- Method 3: Use a ,Code:
lambdaand https://blog.finxter.com/python-lists/ListCode:map()
- Method 4: Use a LoopCode:
for
- Bonus: Calculate Commissions on each List Element
Preparation
These examples use functions from the
Code:
mathAdd the following code to the top of each script. This snippet will allow the code in this article to run error-free.
Code:
import mathMethod 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.
Code:
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
Code:
numsNext, a Generator Expression is called and applies the
Code:
math.pow()Code:
mathCode:
numsIf output to the terminal at this point, an iterable Generator Object similar to the following displays.
Code:
<generator object at 0x000002468D9B59A0>To turn the Generator Object into a https://blog.finxter.com/python-lists/
Code:
ListCode:
print(list(nums))The content of
Code:
nums[324.0, 1849.0, 2916.0, 4225.0, 961.0, 441.0, 729.0]
Note: The Code:
math.pow()Code:
xCode:
yCode:
xCode:
yMethod 2: Use List Comprehension
This example uses List Comprehension to perform an operation on each List element.
Code:
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
Code:
numsNext, List Comprehension is called and applies thehttps://blog.finxter.com/a-guide-to-pyth...-function/
Code:
math.sqrt()Code:
mathCode:
numsIf output to the terminal, the following displays.
Code:
[4.242640687119285, 6.557438524302, 7.3484692283495345, 8.06225774829855, 5.5677643628300215, 4.58257569495584, 5.196152422706632]
Note: The Code:
math.sqrt()Method 3: Use a Lambda and map()
This example uses Python’s
Code:
lambdaCode:
map()Code:
nums = [18, 43, 54, 65, 31, 21, 27]
nums = list(map(lambda x: math.degrees(x), nums))
print(nums)The above code declares a https://blog.finxter.com/python-lists/List of numbers and saves it to the variable
Code:
numsNext, List is called and passed an argument
Code:
map()Code:
lambdaCode:
math.degrees()Code:
mathCode:
LCode:
stCode:
numsIf output to the terminal, the following displays.
Code:
[1031.324031235482, 2463.71851906254, 3093.9720937064453, 3724.225668350351, 1776.169164905552, 1203.2113697747288, 1546.9860468532227]![[Image: 1f4a1.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png)
Code:
NoteCode:
math.degrees()Method 4: Use a For Loop
This example uses a
Code:
forCode:
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 https://blog.finxter.com/python-lists/List of Integers and saves it to the variable
Code:
numsCode:
iNext, a
Code:
whileCode:
math.sqrt()Code:
numsUpon completion of the iteration, the output is sent to the terminal.
Code:
[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
Code:
real-estate.csvThen, the street column is converted from UPPERCASE
Code:
uppercase()Code:
title()Code:
round()Code:
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.
Code:
['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
Code:
ListGood Luck & Happy Coding!
Programming Humor – Python
[i]“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.” — xkcd[/i]

