List and Tuple initialized from string object

python, python-2.7, python-3.x, string, tuples

Solution

Tuples are not determined by parenthesis, they are determined by the comma:

>>> (1)
1
>>> (1,)
(1,)
>>> (1),
(1,)
>>> 1
1
>>> 1,
(1,)

The intermediate parenthesis are removed until an expression is determined:

>>> tuple((((('string')))))
('s', 't', 'r', 'i', 'n', 'g')
>>> tuple((((('string'))),))
('string',)
>>> tuple((((('string'),)),))
(('string',),)

You see how Python parses these expressions by using ast

>>> import ast
>>> ast.literal_eval("((((('string')))))")
'string'
>>> ast.literal_eval("((((('string')))),)")
('string',)

And shows you why `tuple(('string'))` is the same as `tuple('string')`. The extra parenthesis do not create a tuple and are just discarded by the parser.

Problem

How the following two are differ: ``` >>> s = 'string' >>> tuple(s) ('s', 't', 'r', 'i', 'n', 'g') >>> tuple([s]) ('string',) >>> tuple((s)) ('s', 't', 'r', 'i', 'n', 'g') >>> tuple((s,)) ('string',) >>> ``` String is an iterable object thats why it split into multiple element inside the tuple ?

Original source