Puzzling difference between lists and tuples
Ethan Furman
ethan at stoneleaf.us
Thu Sep 17 12:47:14 EDT 2020
On 9/17/20 8:24 AM, William Pearson wrote:
> I am puzzled by the reason for this difference between lists and tuples.
>
> A list of with multiple strings can be reduced to a list with one string with the expected results:
> for n in ['first']:
> print n
['first'] is a list.
> for n in ('first'):
> print n
('first') is not a tuple. The tuple operator is actually the comma:
>>> not_a_tuple = ('first')
>>> type(not_a_tuple)
<class 'str'>
>>> is_a_tuple = 'first',
>>> type(is_a_tuple)
<class 'tuple'>
I tend to use both as it makes it stand out a bit more:
>>> still_a_tuple = ('first', )
>>> type(still_a_tuple)
<class 'tuple'>
The only time the parentheses are required for tuple building is when
they would otherwise not be interpreted that way:
some_func('first', 'second') # some_func called with two str args
some_func(('first', 'second')) # some_func called with one tuple arg
--
~Ethan~
More information about the Python-list
mailing list