0

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?

2
  • 2
    This literal list: [fr[i] != vsi] evaluates to a list with a single boolean value in it. When a non-empty list is being evaluated for truthyness (like what you're doing), it will be considered "truthy". If the list were empty, it would be "falsey".
    – Paul M.
    Dec 21, 2020 at 10:14
  • try breaking out your comparisons. e.g have a method that performs the comparison and returns a result, easier to trace/debug Dec 21, 2020 at 10:16

2 Answers 2

5

[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
1
  • A list can be created without a name? Dec 21, 2020 at 14:26
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.