Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't use semi-colon before for loop in Python?

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 908
Neil Walker Avatar asked Jun 18 '14 18:06

Neil Walker


2 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 122
BrenBarn Avatar answered Sep 17 '22 15:09

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 36
arshajii Avatar answered Sep 17 '22 15:09

arshajii