one-element tuples [Was: Most probably a stupid question, but I still want to ask]
MRAB
python at mrabarnett.plus.com
Sun Apr 10 20:33:10 EDT 2016
On 2016-04-11 01:13, Fillmore wrote:
>
> Sorry guys. It was not my intention to piss off anyone...just trying to understand how the languare works
>
> I guess that the answer to my question is: there is no such thing as a one-element tuple,
> and Python will automatically convert a one-element tuple to a string... hence the
> behavior I observed is explained...
>
> >>> a = ('hello','bonjour')
> >>> b = ('hello')
> >>> b
> 'hello'
> >>> a
> ('hello', 'bonjour')
> >>>
>
>
> Did I get this right this time?
>
Nope. :-)
A one-element tuple can be written as:
>>> ('hello',)
('hello',)
As has been said already, it's the comma that makes the tuple. The
parentheses are often needed to avoid ambiguity.
For example, object are passed into a function thus:
f(x, y)
(In reality, it's making a tuple and then passing that in.)
What if you want to pass in the tuple (1, 2) as a single argument?
f((1, 2))
If you write this:
f(1, 2)
it passes them in as 2 separate arguments.
Or consider this:
f((1, 2), 3)
This has 2 arguments: the first is the tuple (1, 2) and the second is
the int 3.
There _is_ one exception though: (). It's the empty tuple (a 0-element
tuple). It doesn't have a comma and the parentheses are mandatory.
There's no other way to write it.
More information about the Python-list
mailing list