Python while loop

 def merge(l1,l2):
 i=0;
 while((l1[i]!=none)||(l2[i]!=none)):

      

SyntaxError: Invalid syntax being a newbie I can't figure out what's wrong with the abouve code.

+2


a source to share


2 answers


Replace ||

with or

, make None

in uppercase (and lose half a line):

def merge(l1, l2):
  i = 0
  while l1[i] != None or l2[i] != None:
    pass

      

(As you can see, the parentheses were also redundant.)



Alternatively, != None

you can change to is not None

:

while l1[i] is not None or l2[i] is not None:

      

(Thanks to @SilentGhost for pointing this out.)

+12


a source


Even more Pythonic would be something like this (since it looks like you are iterating over both lists until you click No):

for l1val,l2val in zip(l1,l2):
  if l1val is None or l2val is None:
    break
  ... rest of while loop goes here, using l1val and l2val
      instead of l1[i] and l2[i]

      

In fact, that no guard looks strange. If that's what you've stuck with all the way so you know when you're at the end of the list, then don't worry - just use Python's own iteration functions (for loops, they automatically stop at the end of the list they iterate over. *)

for l1val,l2val in zip(l1,l2):
  ... body of while loop goes here, using l1val and l2val
      instead of l1[i] and l2[i]

      

* - They don't stop automatically - the list iterator throws a StopIteration exception, which gets caught in the for loop as a signal to stop the loop.



My crystal ball is getting fluffier, but there is another clue, in your method the name is "merge". Let say merge take two lists, and each list is a list of integers, and by "merge" you mean returning a new list of sums of the corresponding values ​​in l1 and l2. This is what the merge looks like with a for loop:

def merge(l1, l2):
  retl = []
  for v1,v2 in zip(l1, l2):
    retl.append(v1+v2)
  return retl

      

As a beginner, you should learn and gain a very handy concept called list comprehension. Using a list comprehension, you can simplify the merge method to a simple one:

def merge(l1, l2):
  return [v1+v2 for v1,v2 in zip(l1, l2)]

      

This is equivalent to the previous function - study them and see how it works. And finally, at the blinking moment of Python duck typing, run merge as-is, but this time pass it a list of lists instead of a list of int. (Left as an exercise for the OP.)

+4


a source







All Articles