Home >Backend Development >Python Tutorial >How Can I Apply a Function to Each Element of a Python List?

How Can I Apply a Function to Each Element of a Python List?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 20:38:11122browse

How Can I Apply a Function to Each Element of a Python List?

Mapping Functions to List Elements

Suppose you are given a list like:

mylis = ['this is test', 'another test']

You want to apply a function to each element in the list. For instance, you want to apply str.upper to achieve:

['THIS IS TEST', 'ANOTHER TEST']

To achieve this, you can employ list comprehensions. Here's an example:

mylis = ['this is test', 'another test']
[item.upper() for item in mylis]

The result would be:

['THIS IS TEST', 'ANOTHER TEST']

The above is the detailed content of How Can I Apply a Function to Each Element of a Python List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn