Puzzling difference between lists and tuples
Cameron Simpson
cs at cskk.id.au
Sun Sep 20 21:34:55 EDT 2020
On 20Sep2020 20:33, Avi Gross <avigross at verizon.net> wrote:
>('M','R','A','B') is correct. I appreciate the correction. I did not look to
>see the content of what I created, just the type!
>
>>>> a = tuple("first")
>>>> a
>('f', 'i', 'r', 's', 't')
>>>> type(a)
><class 'tuple'>
>
>But I thought adding a comma would help and it does not!
Ah, the comma is for an expression. But you made a function call (well,
"tuple" is a type and types are callable to make instances).
In a function call the parmeter separating commas have higher precedence
than the commas with defines a tuple, you you've made a function call
with one argument "first", not a function call with one _tuple_ argument
("first",).
Consider:
foo(1, 2)
That supplies 2 arguments, not a single tuple.
As with other situations where the default precedence groups things in a
different way from your intent, brackets get required here if you want
to express a tuple.
This:
foo( (1,2) )
isn't notionally different from needing brakcets to express this:
(3+5) * 8
which means something else without its brackets.
Also, function calls allow you to include a trailing comma because it
helps with code. Consider the following bigger call:
x = foo(
1,
2,
fred=5,
)
laid out on separate lines for readability (a little redundant here, but
some complex function calls, or those exceeding the deired line length,
are often folded this way).
Bu allowing a trailing comma we get consistent formatting and nicer
diffs. If a trailing comma were forbidden, the dopping "fred=5" with
produce a diff removing not just that line but also the comma on the
preceeding line. Ugly and noisy.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list