Puzzling difference between lists and tuples

Richard Damon Richard at Damon-Family.org
Thu Sep 17 12:50:05 EDT 2020


On 9/17/20 11: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','second']:
>     print n
>
> for n in ['first']:
>     print n
>
> The first loop prints "first", "second", and the second prints "first".
>
> ====
>
> This is not true for a tuple:
>
> for n in ('first','second'):
>     print n
>
> for n in ('first'):
>     print n
>
>
> prints "first", "second" in the first case, but "f","i","r","s","t" in the second.
>
> Where is this inconsistency explained?
>
Parenthesis don't always make a tuple (and in fact aren't needed to make
them)

('first') is just the string value 'first', inside a set of parenthesis
to possible affect order of operations.

For 1 element tuples, you need a trailing comma, like ('first,) and in
many places it also could be just 'first',

just like your first example could be just for n in 'first', 'second':

-- 
Richard Damon



More information about the Python-list mailing list