My name is Ram Rachum, and I'm a software developer based in Israel, specializing in the Python programming language.

This is my personal blog. I write about technology, programming, Python, and any other thoughts that come to my mind.

I'm sometimes available for freelance work in Python and Django. My expertise is in developing a product from scratch.

GitHub profile

Personal Website

20th December 2011

Text

Silly Python riddle

Here’s a silly Python riddle for you.

Today I opened up a Python 2.7 shell, and ran two commands in it.

>>> f = lambda: g(???)
>>> f()

(Note that these are the only commands that I ran. You’re not allowed to run any other commands before them.)

The riddle: What’s the shortest thing you can put instead of ??? so my second command would not raise an exception?

Edit: I just posted it and people are already coming up with creative solutions! So now it’s time to say: The winning solution is 7 characters long. Try to match that!

———————————

Update: An anonymous commenter on Hacker News solved it!

The solution:

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

(Scroll down…) 

The solution:

>>> f = lambda: g((yield))
>>> f()

Funny, isn’t it? I was surprised to see that the yield keyword can be used in a lambda function. 

So when you type f(), it just returns a generator. If you’ll try to exhaust it, an exception will be raised because g doesn’t exist, but that’s a new line :)

It’s funny that in this case, Python seems to throw away the value of the lambda function! As we know, the yield keyword actually forms an expression whose value is None, unless you used the generator’s .send instead of .next. So you could also use .send to send in whatever value you want into the lambda function, and Python will just throw it away. Unless I’m missing something.

So that’s the only case I can think of where Python completely throws away the value of a lambda function.

Tagged: planetpython

Comments
All content in this website is copyright © 1986-2015 Ram Rachum.
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License, with attribution to "Ram Rachum at ram.rachum.com" including link to ram.rachum.com.
To view a copy of this license, visit: http://creativecommons.org/licenses/by-sa/3.0/