0

I was testing python code and I faced some questions. I've learned that when using conditional statement, if, you need to write conditions that comes out as an boolean value, true ,false.

However, when a list is placed in the position of a conditional expression, Python determines the truthfulness based on whether the list is empty or not.

Why does python determines like that? I want to know what is going on inside python more deeply.

I thought syntax error will occur because I didn't put boolean variable. But code went just right.

The code that I was testing with is here:

programming = ["Python", "Java", "C++"]
math = ["Algebra", "Calculus"]
pe = ["Running", "Swimming"]

if programming and math and pe:
    for i in range(m):
    print(programming[i] + 1, end=' ')
    print(math[i]+ 1, end=' ')
    print(pe[i]+ 1)
else:
    print(0)
Minju Jo
  • 1
  • 1
  • That's how it is for all empty containers. It's useful. – wim Aug 28 '23 at 16:02
  • But exactly why though? Does another programming languages does the same thing? Do lists return True or False according to the emptyness? – Minju Jo Aug 28 '23 at 16:05
  • Any expression you place after the `if` is treated as if converted by the `bool()` function. (This applies to each subexpression). So, in your example you should view the `if` in your head as though you had written: `if bool(programming) and bool(math) and bool(pe):`. (With the sub expressions converted to bools, the `and` operators already return bools). Now your question should be: `"What is the result of bool(x) for each type of 'x' that I ever use?"` – quamrana Aug 28 '23 at 16:05
  • There are lots of idioms where it's useful. E.g. `while listname:` which keeps iterating until the list is empty. – Barmar Aug 28 '23 at 16:07
  • PHP also treats empty arrays as falsey. – Barmar Aug 28 '23 at 16:09

0 Answers0