How to Apply a Function to List Elements

5/5 - (1 vote)

Problem Formulation and Solution Overview

As a Pythonista, coding issues may occur where you need to apply a function against array/matrix elements.

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

The organization Happy Mortgages has six (6) different Mortgage Terms available: 30-Year, 20-Year, 15-Year, 10-Year, 7-Year, and 5-Year terms.

The US Federal Reserve has decided to increase the Mortgage Rate by 1.23%.

πŸ’¬ Question: How would we update the Array/Matrix entries to increase the matrix/array elements accordingly?

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

Consider the following related tutorial if you want to apply a function to column elements instead of the matrix or array.

Related Tutorial: How to Apply a Function to Column Elements?


Before any data manipulation can occur, one (1) new library will require installation.

  • The Pandas library enables access to/from a DataFrame.

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.

Feel free to view the PyCharm installation guide for the required library.

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

import pandas as pd 

Method 1: Use List Comprehension

List Comprehension offers a single-line expression to change all the Mortgage Rates in one fell swoop!

m_terms = [30, 20, 15, 10, 7, 5]
m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9]
m_rates = [round(x*.0123+x, 3) for x in m_rates]

Above is a list of Mortgage Terms (m_terms) available for the six (6) existing Mortgage Rates (m_rates).

In our code, List Comprehension loops through m_rates applying the Mortgage Rate increase to each element accordingly. The round() method trims the decimal places to three (3). The results save back to m_rates.


[4.657, 4.353, 3.644, 4.758, 3.847, 3.948]

Method 2: Use Map and a Lambda

This method is a bit more complex than Method 1. Here we use the map() and lambda functions to accomplish the same task.

m_terms = [30, 20, 15, 10, 7, 5]
m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9]
m_rates = list(map(lambda x : round(x*.0123+x, 3), m_rates))

In this code, we loop through m_rates using map() and passing a lambda as a parameter. The Mortgage Rate increases using the lambda to adust each element accordingly.

The round() method trims the decimal places to three (3). The results save back to m_rates as a list.


[4.657, 4.353, 3.644, 4.758, 3.847, 3.948]

Method 3: Use a For Loop and enumerate()

The for loop is initiated with an index (counter) and an item (element value) for m_rates. This variable is wrapped inside enumerate() as an iterable.

m_terms = [30, 20, 15, 10, 7, 5]
m_rates = [4.6, 4.3, 3.6, 4.7, 3.8, 3.9]

for index, item in enumerate(m_rates):
   m_rates[index] = round(m_rates[index]*.0123+m_rates[index], 3)

print (m_rates)

This code loops through m_rates and applies the Mortgage Rate increase to each element.

The round() method trims the decimal places to three (3). Each element saves accordingly.

In case you need a quick refresher on the enumerate() function, have a look at this video tutorial:

Python enumerate() β€” A Simple Guide


[4.657, 4.353, 3.644, 4.758, 3.847, 3.948]

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!