# How to Apply a Function to a Python List

## 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.

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

`print(list(nums))`

The content of `nums `is as follows.

π‘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.

π‘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 `L`i`st` element. The result returns to `nums`.

If output to the terminal, the following displays.

π‘`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.

## 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

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.

π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!