Search code examples
pythonfunctionmemory-address

Clarification on comparing == functions and memory location


I have some questions/clarifications to ask regarding the code snippet below. Thank you!

cube_a = 2 ** 3
cube_b = 2 ** 3
cube_c = lambda x: x ** 3
cube_d = lambda x: x ** 3
cube_e = lambda x: cube_d
cube_f = lambda cube_d: cube_d
def cube_g(cube_a):
    def cube_h(cube_a):
        return cube_a ** 3
    return cube_h

print(cube_d == cube_e(2)) #True Statement 1
print(cube_d == cube_f(2)) #False Statement 2
print(cube_g(3)(5) == 5 **3 ) #True Statement 3
print(cube_a== cube_b) #True Statement 4
print(cube_c== cube_d) #False Statement 5

I do not understand why statement 1 is true, below is my understanding for the rest of the statements.

Statement 2: a function and another function that return that former function are different

Regarding statement 3: cube_g(3)(5) becomes cube_g(3) which calls cube_h(5) hence returning 5**3

Regarding statement 4: is it true because the functions/code are exactly the same line by line? I tried switching up the order (2 **3 vs 3 **2) and using the id() the address was different.

Regarding statement 5: Every lambda function has its own address?


Solution

  • The statement 1 is true because in cube_e you are just returning the lambda function itself, you are not passing any arguments so it will always return cube_d