How can I put multiple statements in one line?


I know a little bit of comprehensions in Python, but they seem very hard to ‘read’. The way I see it, a comprehension might accomplish the same as the following code:

for i in range(10): if i == 9: print('i equals 9')

This code is much easier to read than how comprehensions currently work, but I’ve noticed you can’t have two :s in one line. This brings me to:

Is there a way I can get the following example into one line?

    if sam[0] != 'harry':
        print('hello',  sam)

Something like this would be great:

try: if sam[0] != 'harry': print('hellp',  sam)

But again I encounter the conflicting :s.

I’d also love to know if there’s a way to run try (or something like it) without except. It seems entirely pointless that I need to put except:pass in there. It’s a wasted line.

Asked By: Rhys



You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python – for good reason!

The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! 😉

And if you would tell us what your real problem is, you might even get a pythonic answer. “Getting something in one line” us usually not a programming problem.

Answered By: Achim

I recommend not doing this…

What you are describing is not a comprehension.

PEP 8 Style Guide for Python Code, which I do recommend, has this to say on compound statements:

  • Compound statements (multiple statements on the same line) are generally discouraged.


      if foo == 'blah':

Rather not:

      if foo == 'blah': do_blah_thing()
      do_one(); do_two(); do_three()

Here is a sample comprehension to make the distinction:

>>> [i for i in xrange(10) if i == 9]
Answered By: johnsyweb

Unfortunately, what you want is not possible with Python (which makes Python close to useless for command-line one-liner programs). Even explicit use of parentheses does not avoid the syntax exception. You can get away with a sequence of simple statements, separated by semicolon:

for i in range(10): print "foo"; print "bar"

But as soon as you add a construct that introduces an indented block (like if), you need the line break. Also,

for i in range(10): print "i equals 9" if i==9 else None

is legal and might approximate what you want.

If you are still determined to use one-liners, see the answer by elecprog.

As for the try ... except thing: It would be totally useless without the except. try says "I want to run this code, but it might throw an exception". If you don’t care about the exception, leave out the try. But as soon as you put it in, you’re saying "I want to handle a potential exception". The pass then says you wish to not handle it specifically. But that means your code will continue running, which it wouldn’t otherwise.

Answered By: ThomasH

You could use the built-in exec statement, eg.:

exec("try: n t if sam[0] != 'harry': n tt print('hello',  sam) nexcept: pass")

Where n is a newline and t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.

Answered By: eprovst

It’s actually possible 😉

# Not PEP 8 compatible^
sam = ['Sam',]
try: print('hello', sam) if sam[0] != 'harry' else rais
except: pass

You can do very ugly stuff in Python like:

def o(s):return ''.join([chr(ord(n) + (13 if 'Z' < n < 'n' or 'N' > n else -13)) if n.isalpha() else n for n in s])

which is a function for ROT13 and Caesar encryption in one line.

Answered By: yamm

Maybe with "and" or "or".

After false, we need to write "or".

After true we need to write "and".


n = 0

def returnsfalse():
    global n
    n = n + 1
    print("false %d" % (n))
    return False

def returnstrue():
    global n
    n = n + 1
    print("true %d" % (n))
    return True

n = 0
returnsfalse() or returnsfalse() or returnsfalse() or returnstrue() and returnsfalse()


false 1
false 2
false 3
true 4
false 5

Or maybe like

(returnsfalse() or true) and (returnstrue() or true) and ...

I got here by searching Google with "how to put multiple statments in one line Python". It does not answer the question directly, but maybe somebody else needs this.

Answered By: Shimon Doodkin

Here is an example:

for i in range(80, 90): print(i, end=" ") if (i!=89) else print(i)


80 81 82 83 84 85 86 87 88 89
Answered By: JZP

I do not incentivise this, but say you’re on the command line, you have nothing but Python and you really need a one-liner, you can do this:

python -c "$(echo -e "a='True'nif a : print 1")"

Here we’re pre-processing n before evaluating Python code.

That’s super hacky! Don’t write code like this.

Answered By: Tiago Lopo

You can now just use semicolons. However, you cannot use if/elif/else statements, for/while loops, and you can’t define functions. The main use of this would be when using imported modules where you don’t have to define any functions or use any if/elif/else/for/while statements/loops.

Here’s an example that takes the artist of a song, the song name, and searches genius for the lyrics:

import bs4, requests; song = input('Input artist then song namen'); print(bs4.BeautifulSoup(requests.get(f'{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())
Answered By: NullableMoh

For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

python -c  "from __future__ import print_functionntry: import numpy; print( numpy.get_include(), end='n' )nexcept:passn" OUTPUT_VARIABLE __numpy_path

This will not work and produce this error:

  File "<string>", line 1
    from __future__ import print_functionntry: import numpy; print( numpy.get_include(), end='n' )nexcept:passn
SyntaxError: unexpected character after line continuation character `

This is because the competition between Bash and Python interpretation of n escape sequences. To solve the problem one can use the $'string' Bash syntax to force n Bash interpretation before the Python one.

To make the example more challenging, I added a typical Python end=..n.. specification in the Python print call: at the end you will be able to get both n interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:

python -c  $'from __future__ import print_functionntry:n import numpy;n print( numpy.get_include(), end="\n" )n print( "Hello" )nexcept:passn' OUTPUT_VARIABLE __numpy_path

That leads to the proper clean output without an error:


Note: this should work as well with exec-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note 2: one could work around the problem by replacing some n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.

Answered By: Pierre13fr

Based on ThomasH’s answer:

for i in range(4): print "i equals 3" if i==3 else None


i equals 3

I propose to update as:

for i in range(4): print("i equals 3") if i==3 else print('', end='')


i equals 3

Note, I am in Python 3 and had to use two print commands. pass after else won’t work.

Answered By: jaydrill

If you want it without try and except, then there is the solution.

If you are trying to print ‘hello’ if ‘harry’ in a list
then the solution is:

'hello' if 'harry' in sam else ''
Answered By: ishaant

There is a possible PEP 8 compatible solution.

Solution to if, else

[print("i equals 9") for i in range(10) if i == 9]

Use a list generation instead of if, else.

I think this is probably a useful trick, which has already stated by comment by ThomasH. So this is a serious solution.

Solution to try, except

print("hello", sam) 
    if "sam" in locals() 
    and hasattr(sam, "__getitem__") 
    and 0 < len(sam) 
    and sam[0] != "harry" 
    else None

Try to deal with how expect would behave by an in-line if statement. This line of code is specialized to deal with the existence of sam[0], thus I couldn’t resolve other general try, except cases.

This is one line of code (=w=). Though if written in exactly one-line, it could be too long to contradict PEP 8 E501. So this is a solution for fun.

  • "sam" in locals checks if sam is a valid variable in the current environment;

  • hasattr(sam, "__getitem__") checks if variable sam could be indexed by sam[n];

  • 0 < len(sam) checks if sam have more than zero items;

  • then check sam[0] != "harry".

  • Warning: This should work when type(sam) == list. Other cases were not tested. If you are sure that sam is a list, then the code would not be too lengthy:

    print("hello", sam) if 0 < len(sam) and sam[0] != "harry" else None

Additional Contents

As other answers (for example, Johnsyweb stated, multiple statements on one line is not preferred (PEP 8 E701). So, for any possible Pythonic (PEP 8) solution, the one-line code may have to avoid explicit if, else and try, except.

As another comment by Thomash stated, a better solution for try, except should using a wrapping function. This adds another lines of code; however, calling the function can not only check sam but also other variables:

def check_harry(name):
        print("hello", name) if name[0] != "harry" else None
    except (NameError, TypeError, IndexError):


This could be a more serious solution. Note that bare except is not recommended due to PEP 8 E722. Although this line of compulsive except: pass seems to be a waste of time (and I actually usually agree with that T_T), there lies some code style consideration.

Answered By: ajz34
sam = ['harry', 'john']

print('hello ' + sam[0] if sam[0] != 'harry' else '')
Answered By: qwerteee

This solution might be complex, but working my

one line of script can


$ test_var=$(python3 -c $"import yaml,sys; yaml_as_dict=(lambda :yaml.safe_load(open(f'{sys.argv[1]}','r').read()))()[sys.argv[2]][sys.argv[3]]; print(yaml_as_dict)" <argv1> <argv2> <argv3>)
$ echo $test_var

How to execute multiline python code from a bash script?

How can I write multi-line code in the Terminal use python?

How to define a bash variable from python EOF

Answered By: P_M
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.