Puzzling difference between lists and tuples
MRAB
python at mrabarnett.plus.com
Thu Sep 17 13:43:39 EDT 2020
On 2020-09-17 17:47, Ethan Furman wrote:
> 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:
>
They're needed for the empty tuple, which doesn't have a comma.
> some_func('first', 'second') # some_func called with two str args
>
> some_func(('first', 'second')) # some_func called with one tuple arg
>
More information about the Python-list
mailing list