views:

488

answers:

10

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))
+8  A: 

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
Except for codegolf, of course, then the semicolons are vital :-)
paxdiablo
wouldn't only 'print "yes"' be better as we know '"exam" in "example"' is true
Anurag Uniyal
Anurag: Perhaps there's a reason why Stephan used the word "example" in this code segment.
jmucchiello
Why would you avoid using the semicolons to avoid statement*s*? Just to avoid confusion for someone reading your code?
day_trader
@_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
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.
Therms
+5  A: 

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
+2  A: 

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

if "exam" in "example": print "yes!"
Dominic Rodger
+5  A: 

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
example is not defined. It needs quotes.
Ewan Todd
What part of example didn't you understand? Every code fragment does not need to declare all of its variables.
jmucchiello
A: 

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

a = 1 if x > 15 else 2

mbehan
+5  A: 
for a in someList:
    list.append(splitColon.split(a))

You can rewrite the above as:

newlist = [splitColon.split(a) for a in someList]
Nick D
+1 for List Comprehension
cschol
In the first instance you use `list` and in the second you use `newlist`. Is there any reason for the change?
Cawas
@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 D
Ok, now I see it. Thanks.
Cawas
+4  A: 

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
+1  A: 

A little bit of logic shows how it can be reduced to one line

step 1

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

step 2: we can directly use 'example' instead of assigning it to a var. first, reducing a line

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

step 3: now we know "exam" in 'example' will alwyas be true, hence redundant, so we can reduce one more line

print "yes!"

:)

Anurag Uniyal
A: 

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"
Dan Monego
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
(The issue here is that `0` evaluates to `False`. The reason that your code *does* work, is because `"firstvalue"` evaluates to `True`.)
Stephan202
This trick pre-dates the ternary operator, and is an approximation at best, given its problems with values whose boolean value is False.
Paul McGuire
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
A: 

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 statement 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 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