0

I wrote some code for iteratively opening some images and I realised that I inadvertently used the same name for the img variable x and for the parameters in the lambda function that converts the greyscale image to a binary of 1 and 0:

for i, x in enumerate(list_images):
  
    image_path = os.path.join(parent_directory, x)
    img = Image.open(image_path).convert('L')
    img = np.array(img.point(lambda x: 1 if x > 127 else 0))  
 

To my surprise, the code did not show any error and it worked normally. I double-checked the results symply changing the lamdba parameter name to other different than x.

My question is: Why is there no conflict between the variable names? Is it because the variable for the lambda function is defined within another scope (the one corresponding to the lambda)?

pedro_galher
  • 334
  • 8
  • 18
  • 1
    Yes. It's a different function with its own parameters. There's no conflict here. You're just unable to access the outer `x` from within the lambda because the name is shadowed, but you don't care about that anyway. – deceze Sep 16 '22 at 07:57
  • Simply put, scope. The scope of the x is with in the lambda function. With in the lambda function your inner x shadows your outer x. Hence it works. The scope of the x in lambda is restricted to the lambda function, and hence cannot be accessed outside, hence it never effects the x outside. – Hassan Jalil Sep 16 '22 at 07:59

1 Answers1

0

Simply put, scope. The scope of the x is with in the lambda function. With in the lambda function your inner x shadows your outer x. Hence it works. The scope of the x in lambda is restricted to the lambda function, and hence cannot be accessed outside, hence it never effects the x outside.

Hassan Jalil
  • 1,114
  • 4
  • 14
  • 34