User Tools

Site Tools


How to apply a function on each element of a list


Suppose that we have a list and we need to apply some function on each element of it.
One good example is getting a file content using readlines(). This function will get every line, including the newline (e.g. \n.)

One thing we can do is this:

r = []
for line in fh.readlines():

But a better way is to use map and a lambda function:

map((lambda(x): x.strip()), self.fh.readlines())

python/listmap.txt · Last modified: 2013/03/16 17:40 (external edit)