Variable name same as lambda function parameter

Viewed 24

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)?

1 Answers

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.

Related