user3335966 user3335966 - 2 years ago 127
Python Question

Python one-liners

Is it real, write program on Python in one line? With tabulation & spaces, but without line breaks. I asked my friend, who sometimes write on Python, about it, but his brain threw exception, because he's never tried to make it.
And yes, I know that it break

The Zen of Python
& this question is stupid, but it's just interesting for me.

Answer Source

First, one-liners are possible, although you have to deviate from typical Python style, separating commands with ; a-la Perl one-liners. For example, here is a particularly weird way to calculate a+1

>>> a=2;b=10**a;print(len(str(b)))

Second, you can do a lot of stuff in a single command, using lambdas, chaining method/attribute calls and maybe wrapping the entire thing in a list comprehension. And reduce or something, while you are at it. This is very prone to producing code that is smart, but takes a lot of time to comprehend, so probably not what you want in the actual work, but it's a near hacker toy. Have a look at Python one-liners page on

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download