+ 10

Why is bool([()])==True but bool(([]))==False ?

My question is based on a challenge. Does anybody have an explanation for this behaviour?

10th Feb 2018, 6:57 AM
Jan Markus
4 odpowiedzi
+ 6
Because 1st bool means list object with tuple value in it i.e [ () ] . Although tuple is empty, it doesn't matter because bool check whether list [] contain something. This leads to True. 2nd bool is false because (( [] )) evaluate to simply [] cuz in case of (( something )) , parenthesis are simply code block. Hope it helps :)
10th Feb 2018, 7:14 AM
Sylar
+ 9
@Sylar & Davy: Thank you both for your explanations! :-) I have just found out that it is possible to get True in both cases, if you write the 2nd case like: print(bool(([],))) Mind the comma! Then it is not just a pair of brackets but a tuple. It is the same problem with (3) and (3,).
10th Feb 2018, 7:55 AM
Jan Markus
+ 4
The first one is a list containing an ( empty) element, making the list not empty, the second one is an empty list.
10th Feb 2018, 7:16 AM
davy hermans
davy hermans - avatar
+ 2
Thanks. I was just wondering how that would work!
10th Feb 2018, 8:02 AM
davy hermans
davy hermans - avatar