Puzzling difference between lists and tuples

Avi Gross avigross at verizon.net
Sun Sep 20 20:33:39 EDT 2020


('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!

>>> b = tuple("first",)
>>> b
('f', 'i', 'r', 's', 't')

Yet something this simple without invoking tuple(), works!

>>> c = 'first',
>>> c
('first',)

So I read the manual page and tuple takes an iterable as an argument and
treats a string as an iterator on characters! It is not a simple
initializer. 

I got around it, sort of, using n array with a single object of type string
in it so the iterator is iterating at a different level.

>>> d = ["first"]
>>> tuple(d)
('first',)
>>> tuple(["first"])
('first',)

I understand the design choice and can imagine there may be another function
that initializes a tuple more directly in some module.

Returning to lurking mode ...

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of MRAB
Sent: Sunday, September 20, 2020 7:35 PM
To: python-list at python.org
Subject: Re: Puzzling difference between lists and tuples

On 2020-09-20 23:59, Avi Gross via Python-list wrote:
> There is a simple and obvious way to make sure you have a tuple by
invoking the keyword/function in making it:
> 
>>>> a=('first')
>>>> type(a)
> <class 'str'>
> 
>>>> a=("first",)
>>>> type(a)
> <class 'tuple'>
> 
>>>> a=tuple("first")
>>>> type(a)
> <class 'tuple'>
> 
> That seems more explicit than adding a trailing comma. It also is a simple
way to make an empty tuple but is there any penalty for using the function
tuple()?
> 
[snip]
 >>> tuple("first")
('f', 'i', 'r', 's', 't')

Not the same as ("first",).

A simpler way to make an empty tuple is just ().
-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list