No loops in Python one-liners?

You can pass to the Python interpreter a one-liner, such as this one:
python -c 'print "hello"'

You can even do fancy things like this:
python -c "import os; print os.listdir('.')"

But it seems you cannot do loops within the line:
python -c "import os; for i in os.listdir('.'): print i"

However, you can do loops as long as it begins the line, as follows:
python -c "for i in range(10): print i; print i"

Interestingly, both “print i” above are considered to be inside the loop. I could not find any documentation anywhere regarding this limitation which seems to derive from how Python parses code lines.

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

4 thoughts on “No loops in Python one-liners?”

  1. You can do loops in the form of list comprehensions.

    import sys,os,re,fileinput;a=[i[2] for i in os.walk(‘.’) if i[2]] [0];[sys.stdout.write(re.sub(‘at’,’op’,j)) for j in fileinput(a,inplace=1)]

    Careful with this one though, it will edit files on your path without prompt!


Leave a Reply

Your email address will not be published. The comment form expects plain text. If you need to format your text, you can use HTML elements such strong, blockquote, cite, code and em. For formatting code as HTML automatically, I recommend

You may subscribe to this blog by email.