Home > other >  Why does python asks for parentheses in list comprehension
Why does python asks for parentheses in list comprehension

Time:07-18

I'm a newbie in coding and I was trying to solve some list questions about iterating both lists at the same time.

My code was this:

list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]

mx = [x,y for x,y in zip(list1, list2[::-1])]

print(mx)

However it didn't work and instead this code worked

list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]

for x, y in zip(list1, list2[::-1]):
    print(x, y)

Not: I couldn't add my code to draft properly sorry :/

Why does the first code throws an error stating "did you forget parentheses around the comprehension target", why is there a need for a parentheses.

CodePudding user response:

I guess originally it is preferred by the authors of python language.

PEP 202 (List comprehensions) explicitly specifies that

The form [x, y for ...] is disallowed; one is required to write [(x, y) for ...].

without telling us the reason, but you can read the mails among the authors. In the thread, you can find

however, I think I prefer

[(x, x*2) for x in seq]

over

[x, x*2 for x in seq]

Another post says:

Nevertheless, FWIW, I prefer

[(x, x*2) for x in seq]

too.

And this seems not be due to ambiguity for parsers, but for human readability. Guido van Rossum says:

If you'd rather not support [x, y for ...] because it's ambiguous (to the human reader, not to the parser!) ...

Indeed, it seems that in the developmental stage, Greg Ewing could implement the following:

[x, x*2 for x in seq]

[(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]

Yep, it works!

But they eventually didn't allow it (probably) in favor of readability.

CodePudding user response:

It is to eliminate scopal ambiguity. Consider the statement:-

"Go to the chemist and on the way home from the chemist visit the butcher and steal his money".

-:it could mean that you should steal from the chemist or from the butcher, depending on where the parentheses are:

Steal from the chemist: "Go to the chemist (and on the way home from the chemist visit the butcher) and steal his money"

Steal from the butcher: "Go to the chemist (and on the way home from the chemist visit the butcher and steal his money)"

So in my example, where the parentheses are placed (and hence the way in which the "steal from" is applied) changes the meaning.

Likewise, "x,y for x,y in..." could mean:

1: "(x), (y for x, y) in..."
2: "(x,y) for (x,y) in..."

And there's actually a few other interpretations.

It was considered better that Python gives an error than tries to interpret ambiguity, hence the insistence on brackets.

See: https://www.philosophyetc.net/2004/08/scopal-ambiguity.html

  • Related