0

Here is a part of a code in Python I try to figure out what it is doing:

while index < len(list) and list[index]: index += 1

I wonder what the part after the "and" (and list[index]) does exactly? I tried to add "is True" or "is False" but both did not yield the same result, so it does not check for True or False I guess. Thanks for any help!

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
kklaw
  • 452
  • 2
  • 4
  • 14
  • The `if` statement in python succeeds not only on `True` but on several other conditions. E.g. `if 1: print('ok')` even though `1 is True` returns `False`. Thus the statement in `list[index]` checks for any of the various true statements which is the negative of what is false, namely `0`,`False`, or `None` (did I miss anyone?). – Dov Grobgeld Jan 28 '21 at 11:40
  • Check [Truthy and Falsy Values in Python](https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/) for discussion of Truthy and Falsy values and their use in while loops and conditionals. – DarrylG Jan 28 '21 at 11:44

2 Answers2

1

It checks for a Truthy value, i.e., a value that does not evaluate to False. Falsy values might include, for example, None, 0, False etc. In a nutshell, the while loop stops at the first Falsy value. For a list of Falsy values, check this answer.

0

"While index value is greater than length of list (index < len(list)) and index value of list is present (list[index]) increment index value by 1."

Example:

list = [1, 2, "three", 333, 30.54, "asdasx"]
index = 0

while index < len(list) and list[index]: 
    print(len(list), list[index])
    index += 1

at 1st iteration list[index] value is 1
at 2nd iteration list[index] value is 2
at 3rd iteration list[index] value is "three" and so on...
until the value for the list[index] is not null it will remain 'True' thus the program will execute.

Raj
  • 80
  • 1
  • 8