Neil Walker Neil Walker - 1 year ago 72
Python Question

Why can't use semi-colon before for loop in 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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download