Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

How to apply a function to all elements of a Python list

Applying a function to each element of a list is such a handy and useful capability that Python has multiple ways to accomplish this task. We will learn all these approaches in this blogpost.

How to apply a function to all elements of a Python list

First, let us determine where you will find a need to apply the same function to all elements of a list. For instance, assume you have a list of numbers representing temperatures in Fahrenheit (degrees F). Let us assume we want to convert all these temperatures in Celsius (degrees C) and arrive at a new list of modified temperatures.

Method 1: Use a for loop

The first approach that might come to your mind is to use a for loop. Here is how that might work.

temperatures = [65,70,75,80,85,90]

def f2c(t):
  val = 5*(t-32)/9
  return (float(f"{val:.2f}"))
  
def convert_temperatures(l):
  newl = []
  for i in l:
    newl.append(f2c(i))
  return(newl)

print("Original list:")
print(temperatures)
print("Converted list:")
print(convert_temperatures(temperatures))

The main takeaway from the code above are the two functions f2c() and convert_temperatures(). f2c() is the function that we wish to apply to all elements of a list. f2c() takes a (single) temperature value in Fahrenheit and converts it to Celsius by applying the usual formula mapping these two temperature scales.

For ease of visual understanding we format the resulting temperature to have at most two numbers after the decimal point and return it as a floating point number. In convert_temperatures we have a for loop that goes through each element of the list, converting it (by using f2c), and adding the resulting value to a newlist which is returned. Finally, temperatures is a list that contains the list of temperatures we wish to convert.

When this program is run, we obtain the expected output:

Original list:
[65, 70, 75, 80, 85, 90]
Converted list:
[18.33, 21.11, 23.89, 26.67, 29.44, 32.22]

Method 2: Use the map() function

The above approach is not that elegant. The map() function intrinsically takes a function and applies it to every element of a list so our code will be much cleaner:

temperatures = [65,70,75,80,85,90]

def f2c(t):
  val = 5*(t-32)/9
  return (float(f"{val:.2f}"))
  
def convert_temperatures(l):
  return (list(map(f2c,l)))

print("Original list:")
print(temperatures)
print("Converted list:")
print(convert_temperatures(temperatures))

Notice the sizable reduction in our convert_temperatures() function. We use the map() function to apply f2c on every element of the input list “l”. This returns a “map object” which is then converted into a list using the list() function. The output is the same as before:

Original list:
[65, 70, 75, 80, 85, 90]
Converted list:
[18.33, 21.11, 23.89, 26.67, 29.44, 32.22]

How simple is that!

Method 3: Use a lambda function

A lambda function in Python is merely a small function that is often defined at the point it is used and thrown away. See the below code for how it applies to our situation. The main difference between this third approach and the previous approach is that we no longer have a separate f2c() function so our code becomes even more succinct:

temperatures = [65,70,75,80,85,90]

def convert_temperatures(l):
  return (list(map(lambda t : float(f"{5*(t-32)/9:.2f}"),l)))

print("Original list:")
print(temperatures)
print("Converted list:")
print(convert_temperatures(temperatures))

We use lambda functions to define a function (without naming it), apply it to each element of a list and print it. The output is again:

Original list:
[65, 70, 75, 80, 85, 90]
Converted list:
[18.33, 21.11, 23.89, 26.67, 29.44, 32.22]

Method 4: Use list comprehensions

Our final approach is to use list comprehensions. Again this gives rise to elegant code. We retain the f2c() function and use list comprehensions to arrive at the converted list of temperatures:

temperatures = [65,70,75,80,85,90]

def f2c(t):
  val = 5*(t-32)/9
  return (float(f"{val:.2f}"))

converted_temperatures = [f2c(x) for x in temperatures]

print("Original list:")
print(temperatures)
print("Converted list:")
print(converted_temperatures)

Note that in this case, we retain the f2c() function but use list comprehension to construct the list of converted temperatures.

So there you have it - four different ways to apply a Python function to each element of a list. Which approach is your favorite? Try them all and let us know!

If you liked this blogpost, learn how to skip values in a Python list.
Also learn how to properly exit a Python function.

For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.