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

Federer picture Federer · Nov 13, 2009 · Viewed 102.4k times · Source

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

Answer

Stephan202 picture Stephan202 · Nov 13, 2009

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.