Are one-line 'if'/'for'-statements good Python style?

Question:

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))
Asked By: Federer

||

Answers:

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.

Answered By: Stephan202

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.

Answered By: Cory Petosky

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

if "exam" in "example": print "yes!"
Answered By: Dominic Rodger

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
Answered By: Ned Batchelder

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

Answered By: Michael Behan
for a in someList:
    list.append(splitColon.split(a))

You can rewrite the above as:

newlist = [splitColon.split(a) for a in someList]
Answered By: Nick Dandoulakis

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.

Answered By: Bryan McLemore

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"
Answered By: Dan Monego

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)()
Answered By: Jim Dennis

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