Tuesday, December 13, 2022

[FIXED] Why does adding a trailing comma after an expression create a tuple?

Issue

Why does adding a trailing comma after an expression create a tuple with the expression's value? E.g. in this code:

>>> abc = 'mystring',
>>> print(abc)
('mystring',)

Why is the printed output ('mystring',), and not just mystring?


Solution

It is the commas, not the parentheses, which are significant. The Python tutorial says:

A tuple consists of a number of values separated by commas

Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.

See the Python Tutorial section on Tuples and Sequences



Answered By - Ben James
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.