Why does Python return [15] for [0xfor x in (1, 2, 3)]? [duplicate]

59

When running the following line:

>>> [0xfor x in (1, 2, 3)]

I expected Python to return an error.

Instead, the REPL returns:

[15]

What can possibly be the reason?

Share
Improve this question
6
  • 32
    Note that Python sees this as [0xf or x in (1, 2, 3)]. You've actually found a minor bug in Stack Overflow's syntax highlighter, as it renders the 0xfor without colouring the or ;) – 101 Apr 14 at 0:40
  • 1
    Quite unexpected... obviously this is useful for codegolfing, but it doesn't feel really consistent at all with the rest of the syntax. IMHO I'd have preferred if strings of consecutive alphanumeric characters were always considered single tokens. – GACy20 Apr 14 at 7:37
  • 1
    I feel like it's a bug in the parser. For the record, it gives the same result with 3or 4 or "hello"and 5. I suspect it's a consequence to accommodate cases for binary operators such as "3>4", but in the case of comparison ops, it's not a straight connection as you can't do 3and5. I posted in python-dev and see what they say – Stefano Borini Apr 14 at 10:25
  • 3
    Storchaka verbatim "it does not contradict specification, but looks pretty confusing, so we will likely change specification and implementation to prevent confusion.". It is also known since 2018. – Stefano Borini Apr 14 at 10:42
  • 2
    @StefanoBorini "hello"and 5 and 3>5 are different. " and > are not valid in identifiers or other forms of expressions. What is unexpected is that a string of pure alphanumeric characters (i.e. [a-z0-9]) can be interpreted as 2 tokens instead of one "randomly" – GACy20 Apr 14 at 12:40

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue