IT_novice
IT_novice

Reputation: 1259

unable to understand lambda map function

Seeking guidance to understand a lambda-map function. In the below, I see that the file "feedback" is read line by line and stored in a list "feedback". I'm unable to get my head around the variable x. I don't see the variable "x" declared anywhere. Can someone help me understand the statement?Thanks in advance

f = open('feedback.txt','r') 
feedback = list(map(lambda x:x[:-1],f.readlines())
f.close()

Upvotes: 0

Views: 391

Answers (4)

Ernesto Herrera
Ernesto Herrera

Reputation: 11

Keep in mind, while explaining lambda is solved here, it is not the implementation of choice for your particular example. Suggestion:

f = open('feedback.txt', 'r')
feedback = f.read().splitlines()
f.close()

See also 'Reading a file without newlines'.

Upvotes: 0

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

lambda function is a simple anonymous function that takes any number of arguments, but has only one expression.

lambda arguments : expression

It is anonymous because we have not assigned it to an object, and thus it has no name.

example f and g are somewhat same:

def f(x):
    # take a string and return all but last value
    return x[:-1]

g = lambda x: x[:-1]

so:

f('hello') == g('hello') #True ->'hell'

But g is not how we would use lambda. The whole aim is to avoid assigning ;)

Now map takes in a function and applies it to an iteratable:it returns a generator in Python 3+ and thus a list is used to case that generator to a list

data = ['we are 101','you are 102','they are 103']

print(list(map(lambda x:x[:-1],data)))

#->['we are 10','you are 10','they are 10']

In principle, same as passing a function:

data = ['we are 101','you are 102','they are 103']

print(list(map(f,data)))

but often faster and awesome. I love lambdas

Upvotes: 0

Bob
Bob

Reputation: 666

The map function will execute the given function for every element in the list.

In your code the map function will get lambda x:x[:-1]. You can read that like: for every x in f.readlines() return everything except the last element of x.

So x will be every line the file. lambda x: you could see as def thing(x):.

Upvotes: 2

Beniamin H
Beniamin H

Reputation: 2086

I replaced lambda with a standard func:

def read_last(x):  #x means a line
  return x[:-1]

f = open('feedback.txt','r') 
feedback = list(map(read_last, f.readlines())
f.close()

Maybe it will help.

Upvotes: 2

Related Questions