PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to create a dictionary containing lambda expressions using comprehension list?

 November 04, 2022     dictionary, lambda, list-comprehension, python     No comments   

Issue

I am trying to generate (something like) the following dictionary:

funcs1 = {
    '0':lambda x:x==0,
    '1':lambda x:x==1,
    '2':lambda x:x==2,
    '3':lambda x:x==3,
    '4':lambda x:x==4,
    '5':lambda x:x==5,
}

I tried to create the dictionary with a list comprehension like this:

funcs2 = {str(i):lambda x:x==i for i in range(0,6)}

Or simply using a for loop:

funcs3 = {}
for i in range(0,6):
    funcs3.update({str(i): lambda x:x==i})

However, funcs2 and funcs3 are not the same as funcs1, for example, when calling the element '0' of each one of them and applying it to 0, the results are different:

funcs1['0'](0)
Out[2]: True

funcs2['0'](0)
Out[3]: False

funcs3['0'](0)
Out[4]: False

Can somebody please help me out and point out where I am making a mistake?


Solution

This is a common misunderstanding caused by Python late binding, this should fix your code:

funcs1 = {
    '0': lambda x: x == 0,
    '1': lambda x: x == 1,
    '2': lambda x: x == 2,
    '3': lambda x: x == 3,
    '4': lambda x: x == 4,
    '5': lambda x: x == 5,
}

funcs2 = {str(i): lambda x, i=i: x == i for i in range(0, 6)}

funcs3 = {}
for i in range(0, 6):
    funcs3.update({str(i): lambda x, i=i: x == i})

print(funcs1['0'](0))
print(funcs2['0'](0))
print(funcs3['0'](0))

Output

True
True
True


Answered By - Dani Mesejo
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing