Dec-27-2019, 10:52 AM
Hi
I saw unexpected Python behavior (to me) with string literals in a list. If I miss a comma in the list sequence, then the two string literals are merged into on string. What I had expected was a syntax error.
In the example below, if I remove the comma between the 'e' and 'i', the list merges the two into 'ei'. The missing comma acts as an implicit + operator.
If I miss a comma between a variable a string literal, or put two commas in a row, I get the Python syntax error I expect.
I want to confirm this merging of literals is correct Python behavior.
To me, Python interpreting the missing comma as an implicit append operator seems error prone. It would be hard to spot a missing comma would be hard to spot in a large list of string literals and a cause of programming bugs.
I saw unexpected Python behavior (to me) with string literals in a list. If I miss a comma in the list sequence, then the two string literals are merged into on string. What I had expected was a syntax error.
In the example below, if I remove the comma between the 'e' and 'i', the list merges the two into 'ei'. The missing comma acts as an implicit + operator.
If I miss a comma between a variable a string literal, or put two commas in a row, I get the Python syntax error I expect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
C:\Users\me>python Python 3.8 . 1 (tags / v3. 8.1 : 1b293b6 , Dec 18 2019 , 23 : 11 : 46 ) [MSC v. 1916 64 bit (AMD64)] on win32 Type "help" , "copyright" , "credits" or "license" for more information. >>> [ 'a' , 'e' , 'i' , 'o' , 'u' ] [ 'a' , 'e' , 'i' , 'o' , 'u' ] >>> [ 'a' , 'e' 'i' , 'o' , 'u' ] [ 'a' , 'ei' , 'o' , 'u' ] >>> [ 'a' , 'e' + 'i' , 'o' , 'u' ] [ 'a' , 'ei' , 'o' , 'u' ] >>> s = 'b' ; [ 'a' , 'e' , s, 'i' , 'o' , 'u' ] [ 'a' , 'e' , 'b' , 'i' , 'o' , 'u' ] >>> s = 'b' ; [ 'a' , 'e' , s 'i' , 'o' , 'u' ] File "<stdin>" , line 1 s = 'b' ; [ 'a' , 'e' , s 'i' , 'o' , 'u' ] ^ SyntaxError: invalid syntax >>> s = 'b' ; [ 'a' , 'e' , , 'i' , 'o' , 'u' ] File "<stdin>" , line 1 s = 'b' ; [ 'a' , 'e' , , 'i' , 'o' , 'u' ] ^ SyntaxError: invalid syntax >>> |
To me, Python interpreting the missing comma as an implicit append operator seems error prone. It would be hard to spot a missing comma would be hard to spot in a large list of string literals and a cause of programming bugs.