Daniel Lemire's blog

, 1 min read

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.