ISSUE I FOUND IN TUPLES
Hello I'm Vinay recently I started learning python and in this process, I noticed there is a glitch in tuples. I don't know whether it's a glitch or not but what I noticed is a list containing single list can identify inner list as a single element of the list whereas in tuples a tuple containing single tuple is unable to identify as a single element unless a comma is specified. # in case of lists a = [[1,2,3]] for i in a: print(i) # this outputs [1,2,3] # in case of tuples a = ((1,2,3)) for i in a: print(i) # outputs as 1 2 3 # but if we specify comma a = ((1,2,3),) for i in a: print(i) # this outputs (1,2,3)
Hi Vinay,
I noticed is a list containing single list can identify inner list as a single element of the list whereas in tuples a tuple containing single tuple is unable to identify as a single element unless a comma is specified.
Thanks for reporting! This is known and documented, quoting the doc [1]:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
This is because parenthesis play multiple roles like describing tuples and mathematical priority: Should: (1 + 1) * 2 be interpreted "twice the tuple containing the result of 1 + 1" which is (2, 2), or the number 4? To disambiguate, the trick is to add a trailing coma:
(1 + 1) * 2 4 (1 + 1, ) * 2 (2, 2)
If you have a better idea, please tell :) If you worry about it, don't, you won't use often tuples of a single element, and it's still possible to build them, so it's OK. [1]: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences -- Julien Palard https://mdk.fr
participants (2)
-
Julien Palard
-
Vinay Godaba