Random Dude
Random Dude

Reputation: 45

Why using square brackets with if doesn't give an error in python

Okay so I am super noob in programming. Wrote a program to find the frequency of each element in an array

print("Running own")
arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];
fr = [None] * len(arr)
vsi = -1
for i in range(0, len(arr)):
    count = 1
    for j in range(i + 1, len(arr)):
        if (arr[i] == arr[j]):
            count += 1
            fr[j] = vsi
            print("j={0} and fr[j]={1}".format(j, fr[j]))
    if [fr[i] != vsi]:
        fr[i] = count
print(fr)

print("fr=", fr)
print("---------------------");
print(" Element | Frequency");
print("---------------------");
for i in range(0, len(fr)):
    if(fr[i] != vsi):
        print("    " + str(arr[i]) + "    |    " + str(fr[i]));
print("---------------------")

so I used square brackets on the if to check if the element is visited and to assign count to the frequency array.(This line: if [fr[i] != vsi]: ) After banging my head against the wall for 5 hours and tracing the program like 20 times I figured out that the compiler is treating if as always true.

Why didn't I get an error to begin with?

Upvotes: 0

Views: 238

Answers (2)

adir abargil
adir abargil

Reputation: 5745

because it is casting the statement into list and the does a boolean check on the resulting list, so even if the inner elemnt is False, the list itself should return True because it is not empty, so even if the syntax is indeed confusing, python statements are available inside the if condition, so this is a valid syntax for python.

it is exactly like doing this:

a=1
b=2 
some_list = [a>b]
if some_list:
    print(f'{some_list} is Truthy')
>>>[False] is Truthy

another demonstration:

[a>b]
Out[10]: [False]
bool([a>b])
Out[11]: True

Upvotes: 1

Shadowcoder
Shadowcoder

Reputation: 972

[fr[i] != vsi ] is a list and it is true whenever there is something inside it.

Examples:

if [0]:  #True
if [1]:  #True
if [""]: #True
if []:   #False

Upvotes: 5

Related Questions