44

Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works.

I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some examples?

For example, could I do this in one line:

example = "example"
if "exam" in example:
    print "yes!"

Or:

for a in someList:
    list.append(splitColon.split(a))
smci
  • 32,567
  • 20
  • 113
  • 146
Federer
  • 33,677
  • 39
  • 93
  • 121
  • 1
    Not sure what you're looking for ... can you explain a bit more? – Adam Liss Nov 13 '09 at 12:51
  • Doesn't Python have those weird lambda thingies nowadays that let you put a whole lot more on a line? Not that I'll ever use them, of course. I prefer the old way of doing things :-) – paxdiablo Nov 13 '09 at 13:06
  • 1
    i've not looked into lambda yet. every time i see that word in a question here i quickly click on a bookmark! – Federer Nov 13 '09 at 13:09
  • 1
    I think she/he is referring to list comprehensions. – Dominic Bou-Samra Nov 13 '09 at 13:15
  • @DominicBou-Samra: at first I also thought OP was asking about list comprehensions, but on closer inspection they only meant *"either one-liner if-statements or for-statements"* – smci Nov 17 '17 at 19:33

10 Answers10

56

Well,

if "exam" in "example": print "yes!"

Is this an improvement? No. You could even add more statements to the body of the if-clause by separating them with a semicolon. I recommend against that though.

Stephan202
  • 59,965
  • 13
  • 127
  • 133
  • 6
    Except for codegolf, of course, then the semicolons are vital :-) – paxdiablo Nov 13 '09 at 13:07
  • wouldn't only 'print "yes"' be better as we know '"exam" in "example"' is true – Anurag Uniyal Nov 13 '09 at 14:04
  • 8
    Anurag: Perhaps there's a reason why Stephan used the word "example" in this code segment. – jmucchiello Nov 13 '09 at 14:15
  • Why would you avoid using the semicolons to avoid statement*s*? Just to avoid confusion for someone reading your code? – Federer Nov 13 '09 at 14:16
  • 4
    @_bravado: correct. I think you can leave out the word 'just': readability is an important guideline in programming. Putting multiple statements on a single line is frowned upon in most languages, but even more so in Python. It's considered unpythonic, at least in part because it's not in line with the philosophy on which the decision for significant whitespace is based. – Stephan202 Nov 13 '09 at 14:31
  • 2
    Not even for just "someone" reading your code...for yourself as well! You'd be surprised at how hard it can be to read your own code if you haven't looked at it in even a short amount of time. – Dustin Wyatt Nov 15 '09 at 04:42
  • This answer seems to go against the PEP8 coding standard. – Vladius Feb 21 '15 at 11:39
  • 2
    @Vladius: the *code snippet* does, yes. The answer as a whole recommends against this style, precisely because of PEP-8. (Should perhaps have made that clearer, over five years ago.) – Stephan202 Feb 21 '15 at 14:05
  • I think that IS an improvement. Many purists will insist one liners are always bad style but, as PEP-8 states: A Foolish Consistency is the Hobgoblin of Little Minds. Guidelines are not dogma. I find one liners read better as long as they are simple. What is the point of spending two lines on a statement like if(x>y): break? It's a single short thought, expressing it as a single line is clearly natural and "readable". If you find yourself with a 40+ char line, or are tempted to start using semi-colons then stop, chances are you've gone too far, but used tastefully I think one liners are great. – Roger Heathcote Jan 10 '20 at 14:41
43

I've found that in the majority of cases doing block clauses on one line is a bad idea.

It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.

In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:

newlist = [splitColon.split(a) for a in someList]

although unless you need a reusable list specifically you may want to consider using a generator instead

listgen = (splitColon.split(a) for a in someList)

note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.

There is also a built in ternary operator in modern versions of python that allow you to do things like

string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print

or

iterator = max_value if iterator > max_value else iterator

Some people may find these more readable and usable than the similar if (condition): block.

When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.

Bryan McLemore
  • 6,438
  • 1
  • 26
  • 30
  • 1
    I've found the ternary operator useful for cases such as `logging.info("Found %d %s", num_results, "result" if num_results == 1 else "results")`. – Dennis Mar 03 '13 at 22:35
  • 3
    I actually really like python's ternary. Once you're used to it it is a lot more readable than most languages. It makes the historic ` ? : ` seem pretty archaic. – Bryan McLemore May 28 '13 at 19:29
20

More generally, all of the following are valid syntactically:

if condition:
    do_something()


if condition: do_something()

if condition:
    do_something()
    do_something_else()

if condition: do_something(); do_something_else()

...etc.

Cory Petosky
  • 12,458
  • 3
  • 39
  • 44
  • 3
    finally semicolons.. that i've been searching for! – holms Mar 20 '13 at 09:31
  • 1
    To be clear, please don't actually use semicolons like this! I was just trying to answer the question completely. – Cory Petosky Mar 21 '13 at 01:43
  • any reason for that? tha's simplifies my life on some if statements, followed by print statements, followed by sys.exit() – holms Mar 23 '13 at 01:06
  • 2
    It makes your code impossible to read by anyone but you. It's just not stylish or idiomatic Python. – Cory Petosky Mar 25 '13 at 21:46
  • To piggyback on @CoryPetosky 's comment, it's also not recommended by PEP8. If you don't feel like digging through the actual guide, just run any pep8 linter on code containing something like `if condition: do_stuff(to, args)`. Pylama flags it as an error under PEP8, not even a warning. – W. MacTurk Jun 03 '21 at 16:01
12

an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version

a = 1 if x > 15 else 2

Michael Behan
  • 3,433
  • 2
  • 28
  • 38
7
for a in someList:
    list.append(splitColon.split(a))

You can rewrite the above as:

newlist = [splitColon.split(a) for a in someList]
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
  • In the first instance you use `list` and in the second you use `newlist`. Is there any reason for the change? – cregox Apr 14 '10 at 20:10
  • 2
    @Cawas, oh, indeed. The OP used "list" in his code. It's not a good practice to *shadow* built-in function or type names, ie the "list". That's why I used "newlist" in my answer. – Nick Dandoulakis Apr 14 '10 at 21:19
6

Python lets you put the indented clause on the same line if it's only one line:

if "exam" in example: print "yes!"

def squared(x): return x * x

class MyException(Exception): pass
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
4

You could do all of that in one line by omitting the example variable:

if "exam" in "example": print "yes!"
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
4

Older versions of Python would only allow a single simple statement after for ...: if ...: or similar block introductory statements.

I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:

for i in range(3): print "Here's i:"; print i

... but, on the other hand, we can't:

for i in range(3): if i % 2: print "That's odd!"

We can:

x=10
while x > 0: print x; x-=1

... but we can't:

x=10; while x > 0: print x; x-=1

... and so on.

In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.

It's marginally acceptable to combine multiple statements on a line in some cases. For example:

x=0; y=1

... or even:

if some_condition(): break

... for simple break continue and even return statements or assigments.

In particular if one needs to use a series of elif one might use something like:

if     keystroke == 'q':   break
elif   keystroke == 'c':   action='continue'
elif   keystroke == 'd':   action='delete'
# ...
else:                      action='ask again'

... then you might not irk your colleagues too much. (However, chains of elif like that scream to be refactored into a dispatch table ... a dictionary that might look more like:

dispatch = {
    'q': foo.break,
    'c': foo.continue,
    'd': foo.delete
    }


# ...
while True:
    key = SomeGetKey()
    dispatch.get(key, foo.try_again)()
Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
0

Dive into python has a bit where he talks about what he calls the and-or trick, which seems like an effective way to cram complex logic into a single line.

Basically, it simulates the ternary operater in c, by giving you a way to test for truth and return a value based on that. For example:

>>> (1 and ["firstvalue"] or ["secondvalue"])[0]
"firstvalue"
>>> (0 and ["firstvalue"] or ["secondvalue"])[0]
"secondvalue"
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Dan Monego
  • 9,637
  • 6
  • 37
  • 72
  • 1
    Be careful: this does *not* simulate C's ternary operator. `1 ? 0 : 2` equals `0`, but `1 and 0 or 2` equals `2`. It's much safer to use another construct which is made precisely for this purpose: `0 if 1 else 2` (which *will* yield `0`). – Stephan202 Nov 13 '09 at 15:31
  • (The issue here is that `0` evaluates to `False`. The reason that your code *does* work, is because `"firstvalue"` evaluates to `True`.) – Stephan202 Nov 13 '09 at 15:32
  • This trick pre-dates the ternary operator, and is an approximation at best, given its problems with values whose boolean value is False. – PaulMcG Nov 13 '09 at 15:36
  • The link I've included covers that, and presents a workaround. I opted for the simpler version, but given the response, it looks like I should put up the safe way to do this. – Dan Monego Nov 13 '09 at 16:03
0

This is an example of "if else" with actions.

>>> def fun(num):
    print 'This is %d' % num
>>> fun(10) if 10 > 0 else fun(2)
this is 10
OR
>>> fun(10) if 10 < 0 else 1
1
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63