Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Why can parentheses cause exceptions in Python when using for loops?
Using parentheses in Javascript is always needed when you want to create functions, if
/else
statements and for
/while
loops. But in Python it has a function that is called tuples. When using an if
statement for example, it won't be a big deal when I use parentheses. But when it comes to for
...in
loops it seems to cause exceptions. For example,
fruits = ["Apple", "Banana", "Orange"]
for (fruit in fruits):
print(fruit)
This will return an exception, SyntaxError: invalid syntax
But when I remove the parentheses it will work again. Is this because the parentheses that act as a tuple prevent the for
...in
loop from iterating over the list and setting a value from the list to fruit
? Which makes it not possible to be printed?
1 answer
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Bennshinpoes |
Thread: Works for me This is a better explanation that I have expected! I have learned alot from this answer, thank you so much. |
May 7, 2023 at 14:45 |
A single element tuple has a trailing comma
Note that the example in the question does not form a tuple, as there is a special syntax for single element tuples. A single element tuple has a trailing comma after its single element. This is necessary to distinguish the single element tuple from an expression that has been enclosed in parentheses to control the order of calculation.
a = (1) # a == 1 (not a tuple)
b = (1,) # b == (1,) (a tuple)
This allows writing the following to control order of calculation, without accidentally making (1 + 1)
a tuple:
c = 2 * (1 + 1) # c == 4
No problem with if
An if
block starts with a line of the following form:
if expression:
Here expression
can be any expression that Python can evaluate to a boolean (True or False). Wrapping an expression in parentheses does not make it a tuple, due to it lacking the required trailing comma for a single element tuple. The enclosing parentheses are therefore interpreted as affecting the order of calculation. Since they enclose the entire expression, there is nothing else to calculate afterwards, so they have no effect. The following 2 lines are therefore equivalent:
if 1 + 1 == 2:
if (1 + 1 == 2):
Problem with for
A for
block starts with a line of the following form:
for variable in iterable:
Here variable
is any valid Python variable name[1], and iterable
is any valid Python expression that evaluates to something that can be iterated over.
As before, an expression enclosed in parentheses is equivalent to the original expression, so the following 2 lines are equivalent:
for fruit in ["Apple", "Banana", "Orange"]:
for fruit in (["Apple", "Banana", "Orange"]):
In the same way, enclosing a variable in parentheses has no effect, so the following 2 lines are equivalent:
for fruit in ["Apple", "Banana", "Orange"]:
for (fruit) in ["Apple", "Banana", "Orange"]:
The problem is caused by also enclosing the in
in parentheses. This causes (fruit in ["Apple", "Banana", "Orange"])
to be interpreted as a single expression. This is the cause of the invalid syntax that Python complains about:
for (fruit in ["Apple", "Banana", "Orange"]):
is interpreted as the invalid
for expression:
instead of
for variable in iterable:
Different meaning of in
when not part of a for
loop
When the parentheses make in
part of a separate expression (fruit in ["Apple", "Banana", "Orange"])
, rather than part of the for
loop, in
takes on its other meaning in Python: Checking for presence of an item in a container.
"Banana" in ["Apple", "Banana", "Orange"] # True
"Grape" in ["Apple", "Banana", "Orange"] # False
-
This is oversimplified to keep the explanation brief - there can in fact be several variables in a single
for
loop, potentially including several layers of destructuring. This is omitted here as it is not relevant to why the parentheses cause a problem. ↩︎
3 comment threads