+ 7

Tuples inside a list

There is a challenge question with code: my_list = [([]), [()]] for i in my_list: print(bool(i), sep=' ') Can anybody explain why is the output 'False True'?

23rd Jan 2020, 4:37 PM
SergeiRom
4 Respuestas
+ 6
Your outer list has two comma-separated elements, ([]) and [()]. The first set of parentheses just disappears, because you can't write a tuple like that. The syntax for a single-element tuple would be: ([],) The syntax for an *empty* tuple on the other hand is (). So parentheses with 0 or 2+ elements are tuples, while parentheses with 1 element just work for grouping unless you add a comma.
23rd Jan 2020, 5:28 PM
HonFu
HonFu - avatar
+ 7
HonFu thank you very much, now it is clearer for me.
23rd Jan 2020, 5:32 PM
SergeiRom
+ 6
I know about empty-False, but why as of the first item () is expression grouping and as of the second expression it is an empty tuple when the both ()'s are inside a list?
23rd Jan 2020, 4:55 PM
SergeiRom
+ 3
Sergei Romanov () this is considers as empty as nothing is present inside the parenthesis. but when it's inside any list then it considered as an list elements. [] this is considered as an empty list without tuple. ([]) this whole statement is considered as empty so bool i when refere to index 0 elements it return false as it reading empty thing which is give false by bool. The parentheses in ([]) just reorders the expression which in the end is just the same thing as [] [()] is an empty tuple in a list When converting any container to a bool, an empty container is False, otherwise it is True my_list is[ [], [()] ] so the for loop iterates twice bool( [] ) == False bool( [()] ) == True (because the list is not actually empty; it contains an empty tuple)
23rd Jan 2020, 4:49 PM
DishaAhuja
DishaAhuja - avatar