Sick Gaming
[Tut] How to Apply a Function to a List - Printable Version

+- Sick Gaming (https://sickgaming.net)
+-- Forum: Programming (https://sickgaming.net/forum-76.html)
+--- Forum: Python (https://sickgaming.net/forum-83.html)
+--- Thread: [Tut] How to Apply a Function to a List (/thread-99942.html)



[Tut] How to Apply a Function to a List - xSicKxBot - 09-13-2022

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.

[Image: 1f4ac.png] 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
Code:
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.

Code:
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.

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:
nums
.

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

If 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:
List
, run the following code.

Code:
print(list(nums))

The content of
Code:
nums
is 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]

[Image: 1f4a1.png]Note: The
Code:
math.pow()
function accepts two (2) integers as arguments:
Code:
x
(the value) and
Code:
y
(the power), and returns the value of
Code:
x
raised to the power of
Code:
y
.

Method 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:
nums
.

Next, List Comprehension is called and applies thehttps://blog.finxter.com/a-guide-to-pythons-pow-function/
Code:
math.sqrt()
function from Python’s built-in
Code:
math
library to each https://blog.finxter.com/python-lists/List element. The results save back to
Code:
nums
.

If output to the terminal, the following displays.

Code:
[4.242640687119285, 6.557438524302, 7.3484692283495345, 8.06225774829855, 5.5677643628300215, 4.58257569495584, 5.196152422706632]

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

[Image: 1f4a1.png]Note: The
Code:
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
Code:
lambda
function combined with
Code:
map()
and https://blog.finxter.com/python-lists/List to apply a mathematical operation to each List element.

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:
nums
.

Next, List is called and passed an argument
Code:
map()
, which in turn passes the
Code:
lambda
function to apply the
Code:
math.degrees()
function from Python’s built-in
Code:
math
library to each https://blog.finxter.com/python-lists/
Code:
L
i
Code:
st
element. The result returns to
Code:
nums
.

If output to the terminal, the following displays.

Code:
[1031.324031235482, 2463.71851906254, 3093.9720937064453, 3724.225668350351, 1776.169164905552, 1203.2113697747288, 1546.9860468532227]

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

[Image: 1f4a1.png]
Code:
Note
: The
Code:
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
Code:
for
Loop to apply a mathematical operation to each List element.

Code:
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:
nums
. Then, a counter variable,
Code:
i
is declared, set to 0.

Next, a
Code:
while
loop is instantiated and iterates through each List element, applying the https://blog.finxter.com/a-guide-to-pythons-pow-function/
Code:
math.sqrt()
function, and limiting the decimal places to two (2). The results save back to the appropriate element in
Code:
nums
.

Upon 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.csv
file, the street and price columns and converts each into a List.

Then, the street column is converted from UPPERCASE
Code:
uppercase()
to Title Case by applying the https://blog.finxter.com/python-string-title/
Code:
title()
function. Next, Sales Commissions are calculated and applied to each price element using
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]

[Image: 1f31f.png]Finxter Challenge!
Convert these Lists into a Dictionary format.

Summary

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

Good Luck & Happy Coding!

Programming Humor – Python

[Image: image-65.png][i]“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.” — xkcd[/i]