Understanding lambda functions

2024/10/10 10:27:45

Well I did try to read about Lambda functions but did not get across any link which explains few questions about its flow and the way it is handled by python interpretor or may be I could not understand it properly. I have few question, please can somebody clarify them for me. Here is the code :

def f1(n):print 'in f1, value is : ', nreturn lambda x: x+nif __name__ == '__main__':f= f1(100)print f(1)print f(3)print f1(10)print f(5)print type(f1)

The output being :

in f1, value is :  100
101
103
in f1, value is :  10
<function <lambda> at 0x019C66B0>
105
<type 'function'>

My question is :

  • For f(1) and f(3) why print statement was not called and when we called f1(100) why lambda statement was not compiled.
  • What is the relation between x and n in function f1.
  • I thought f(5) will 15 ( 10 + 5)
  • Please explain print f1(10)
  • Also, please let me know what is lambda x: means here, is that x name of this block? please explain.

Thanks all.

Answer

First you should understand that everything in Python is an object. And functions do come in everything.

From your function f1(), you are actually returning a reference to a lambda function. Which you can assign in any variable.

For e.g.:

>>> f = lambda x: x   # Assign reference to lambda function to f.
# Now you can call lambda function using `f`  
>>> f(1)
1

Now, let's move ahead with your example. Your first statement is inside if is:

f = f1(100)

This assignment is equivalent to:

f = lambda x: x + 100  # Replace `n` with `100` in return statment in `f1`.

So, the next two call is pretty straighforward:

print f(1)  # returns `1 + 100` = 101 (Replace `x` with `1`.
print f(3)  # returns `3 + 100` = 103

So, now you get the relation between x and n. 'x' is replaced by the argument to f and 'n' is replaced by argument to f1.

Please explain print f1(10)

f1() returns a reference to a lambda function. And that is what it will print. The output is similar to the one which you get in the below snippet:

>>> def func():return 5>>> func
<function func at 0x021F0F30>

Except that func is replaced with lambda, since f1 returns a lambda function only.

I thought f(5) will 15 ( 10 + 5)

You would have got that output, had you re-assigned the return value of f1 to f in the previous statement. But, since you have just printed the value of f(10), f is still binded to - lambda x: x + 100. So you get 105.

And then you print the type of f1, which is a function only:

print type(f1)
https://en.xdnf.cn/q/118467.html

Related Q&A

JSON to Python dataframe: mapping values from another API

I have an API with student data like this, for every student id there will be a corresponding API link with mark details. for example: https://api.school.com/2020/students.json {"Students": […

Create a cycle out of scattered points

I know this sounds trivial, but my head is refusing to give an algorithm for this.I have a bunch of points scattered on a 2-D plane and want to store them in a list such that they create a ring. The po…

Python Dictionary w/ 2 Keys?

Can I have a python dictionary with 2 same keys, but with different elements?

Tkinter throwing a KeyError when trying to change frames

Im learning tkinter off of the Sentdex tutorials and I into a problem when trying to change pages. My compiler throws something about a KeyError that it doesnt give whenever I change the button on the …

How to send messages to other clients only in the sequence of adding clients?

https://github.com/kakkarotssj/ChatApplication/blob/master/GroupChat/sever.pyhttps://github.com/kakkarotssj/ChatApplication/blob/master/GroupChat/client.pyWhen server starts, and suppose three clients …

Dictionary keeps getting overwritten in each iteration of for-loop

import randomo=[,,!,@,#,$,%,^,&,*,(,),,_,=,+,/,[] q=[1,2,3,4,5,6,7,8,9,0]for i in top_25:wordDic ={i: random.choice(o)+random.choice(q)} print(wordDic)(top_25 is an array of words, and the random.c…

Python socket communication with HP print server [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic because it lacks sufficient information to diagnose the proble…

Why are torch.version.cuda and deviceQuery reporting different versions?

I have a doubt about the CUDA version installed on my system and being effectively used by my software. I have done some research online but could not find a solution to my doubt. The issue which helpe…

How to have 2 advertisements in BLE(BlueTooth Low Energy)?

Im working on BLE advertisement. Id like to know if its possible to have 2 advertisements in BLE. I need to have both service data and manufacturer data. Im using Python. The code is based on https://g…

How to get Python script to write to existing sheet

I am writing a Python script and stuck on one of the early steps. I am opening an existing sheet and want to add two columns so I have used this:#import the writer import xlwt #import the reader impor…