Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List and Tuple initialized from string object

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 ?

like image 992
James Avatar asked Jan 11 '23 17:01

James


1 Answers

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.

like image 180
dawg Avatar answered Jan 18 '23 10:01

dawg