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
Release: 2024-12-02 20:38:11
Original
177 people have browsed it

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']
Copy after login

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']
Copy after login
Copy after login

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

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

The result would be:

['THIS IS TEST', 'ANOTHER TEST']
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template