Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating commands with semicolons in Python [duplicate]

Tags:

python

I can join lines in Python using semi-colon, e.g.

a=5; b=10

But why can't I do the same with for

x=['a','b']; for i,j in enumerate(x): print(i,":", j)
like image 349
Neil Walker Avatar asked Jun 18 '14 18:06

Neil Walker


4 Answers

Because the Python grammar disallows it. See the documentation:

stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

Semicolons can only be used to separate simple statements (not compound statements like for). And, really, there's almost no reason to ever use them even for that. Just use separate lines. Python isn't designed to make it convenient to jam lots of code onto one line.

like image 115
BrenBarn Avatar answered Nov 09 '22 08:11

BrenBarn


The short (yet valid) answer is simply "because the language grammar isn't defined to allow it". As for why that's the case, it's hard if not impossible to be sure unless you ask whoever came up with that portion of the grammar, but I imagine it's due to readability, which is one of the goals of Python1.

Why would you ever want to write something obscure like that? Just split it up into multiple lines:

x = ['a','b']
for i,j in enumerate(x):
    print(i, ":", j)

I would argue that this variant is much clearer.


1 From import this: Readability counts.

like image 43
arshajii Avatar answered Nov 09 '22 09:11

arshajii


Because Guido van Rossum, the creator of Python, and other developers, don't actually like the "semicolons and braces" style of code formatting.

For a brief look at how they feel about these things, try:

from __future__ import braces

Statements in Python are supposed to be separated by blank lines, and compound statements in Python are supposed to be bounded by indentation.

The existence of ; and one-line compound statements (e.g. for i in x: print i) are meant to be only very limited concessions... and you can't combine them.

like image 24
Dan Lenski Avatar answered Nov 09 '22 10:11

Dan Lenski


The grammar of Python does not allow this. It's a good answer, but what's the reason for it?

I think the logic behind the decision is the following: body of a for loop must be indented in order to be recognized. So, if we allow not a simple_stmt there, it would require a complex and easy-to-break indentation.

like image 24
Dmytro Sirenko Avatar answered Nov 09 '22 08:11

Dmytro Sirenko