-4

I would like to know what if the difference with and without square bracket

Here is my code without square bracket in the if statement, which answer is correct.

a=[3,90,3,7,8,100]
if sum(a)<100:
    a.append(2)
print(a)

While if I put the square bracket, it will be wrong, Can anyone explain it to me?

a=[3,90,3,7,8,100]
if [sum(a)<100]:
    a.append(2)
print(a)
  • Why would you attempt to put the expression in square brackets in the first place? This is Python not bash. – blhsing Dec 23 '20 at 07:08
  • @blhsing yea! but I want to know what does this mean in python – Grace Cheng Dec 23 '20 at 07:09
  • You are checking `bool([sum(a)<100])`. which will always be `True`. – Countour-Integral Dec 23 '20 at 07:10
  • 1
    Square brackets in Python are reserved for `list`s or getitem/slicing operation. If you write `if [sum(a) < 100]` this is equivalent to: `some_list = [sum(a) < 100]; if some_list:`. Now, any non-empty `list` will evaluate to `True` ("truthy"), regardless of the content, e.g. `bool([False]) == True` while `bool([]) == False`. – norok2 Dec 23 '20 at 07:11

4 Answers4

0

So when you use the square brakets, python check whether the list is empty rather then the value inside the list.

This is always interpreted as True, thus the wrong results.

Example to emphasize it:

l = [True]
if l:
    print("test")

l = [False]
if l:
    print("test")

Both cases will print "test".

David
  • 8,113
  • 2
  • 17
  • 36
0
a=[3,90,3,7,8,100] # in python lists are denoted by square brackets
if sum(a)<100:  # Here sum(a) means sum([3,90,...]) it's a list and it can add all. 
    a.append(2) # append means adding new element at end of the list a
print(a)
a=[3,90,3,7,8,100] 
if [sum(a)<100]: # here the condition will be always true because [True] is not empty
    a.append(2)
print(a)
Nanthakumar J J
  • 860
  • 1
  • 7
  • 22
0

The check is if the list is empty. See the below for explanation

>>> [sum(a)<100]
[False]
>>> if [False]:
...   print('hello')
...
hello
>>> if []:
...   print('hello')
...
>>>
Aaj Kaal
  • 1,205
  • 1
  • 9
  • 8
0

if [sum(a)<100]: can be understand as: if [False]:. And [False] will be interpreted as True in if statement (see this). So if statement will be execute.

namgold
  • 1,009
  • 1
  • 11
  • 32