Home >Backend Development >Python Tutorial >How Can I Modify a List of Strings Using a Function in Python?
Modifying List Elements with Functions
Suppose we're given a list containing strings, such as:
mylis = ['this is test', 'another test']
We aim to modify each element in the list by applying a specific function, for instance, str.upper to get:
['THIS IS TEST', 'ANOTHER TEST']
Solution: Utilizing List Comprehension
One efficient approach to achieve this modification is by utilizing list comprehension:
[item.upper() for item in mylis]
In this comprehension, for each item in the original list mylis, the str.upper method is applied to convert it to uppercase. The result is a new list containing the modified elements.
The above is the detailed content of How Can I Modify a List of Strings Using a Function in Python?. For more information, please follow other related articles on the PHP Chinese website!