Python Applying a Function To Each Element Of The List
To apply a function to each element of a list in Python, you can use one of these methods:
The map() function which takes a function and one or more iterables as arguments and returns a map object that you can convert to a list using list().
A list comprehension which creates a new list by applying an expression to each element of an existing list.
A for loop which iterates over each element of a list and applies a function to it.
Here is an example of each method using the upper() function from the string module:
from string import upper
mylis = ['this is test', 'another test']
# Using map()
mapped = map(upper, mylis)
print(list(mapped))
# Using list comprehension
comp = [upper(x) for x in mylis]
print(comp)
# Using for loop
for i in range(len(mylis)):
mylis[i] = upper(mylis[i])
print(mylis)
The output of each method is:
['THIS IS TEST', 'ANOTHER TEST']
['THIS IS TEST', 'ANOTHER TEST']
['THIS IS TEST', 'ANOTHER TEST']
Use the map function to apply the same transformation to every element in a List.
ID = ["R72345","R72345&"]
results = list(map(str.isalnum, ID))
print(results)
# output [True, False]
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment