Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop conditions in: compound conditional expressions AND'd [python]

Apologies for the really trivial introductory level python question.

Currently working through Google Python tutorials and hit something which may trip me up if I don't nail it down - using and'd values as a compound condition for execution of a while loop.

Reading through it appears as if the while loop operates whilst the length of both lists are positive. So once the length of both lists == 0, then the while loop hits a 0 and terminates.

I'm unsure of how to parse this mentally - whether the condition is that once both lengths == 0 then the and statement and's 0 and 0, giving a negative condition and terminates.

Reading it through I parse it as while '5' and '6' (if for instance 5 and 6 are the len of lists). I've not come across use of a while loop in this way so far (only been going for a day or so).

Code bit I don't get (abstract lines)

while len(list1) and len(list2):

Code in context

def linear_merge(list1, list2):

  result = []     
  while len(list1) and len(list2):
    if list1[0] < list2[0]:
      result.append(list1.pop(0))
    else:
      result.append(list2.pop(0))    

  result.extend(list1)
  result.extend(list2)
  return result

Thanks kindly.

like image 771
Rob L Avatar asked Feb 16 '23 17:02

Rob L


2 Answers

while len(list1) and len(list2):

Will continue to loop while both list1 and list2 are not empty; if either list is empty, the loop will terminate.

(In a boolean context, any value except False, None, 0, "", or [] will evaluate as true.)

like image 168
Wooble Avatar answered Feb 19 '23 10:02

Wooble


Quoting Built In Types Page on Official Python documentation:

x and y give the result according to: if x is false, then x, else y

Further on this page it is mentioned that:

This is a short-circuit operator, so it only evaluates the second argument if the first one is True

So in your question, it first evaluates len(list1). If it is positive, the first condition is True and next it evaluates the second condition. If that is also True (i.e. len(list2)>=1), it enters into the loop. While fundamentally it is an AND operation, it differs in the sense that we don't need to evaluate the second condition, if the first one is False. This can be very helpful in certain cases, when the second condition may involve time consuming calculations.

like image 35
Nipun Batra Avatar answered Feb 19 '23 10:02

Nipun Batra