Hi there. I am fairly new with python and programming altogether. I'm having a problem dividing elements of two lists, and appending the results to a new list. The problem is, the second list may contain a zero, and obviously we can't divide by zero. If it happens that we need to divide by zero, I'd just like to append a zero in my new list for that position. Below I have posted my final attempt at trying to code this. I'm getting an invalid syntax at "if b==0:". Any help will be much appreciated.

a = [3, 7, 6, 4]
b = [1, 7, 0, 2]

#Expected result after dividing a by b
# c = [3, 1, 0, 2]

count = 0
c = []
d = 0

while count < len(a):


    if b ==0:  #invalid syntax error

    count = count + 1


Edited 3 Years Ago by pyTony: cleaned partially the formatting, take care yourself next time!

  1. first solution: c.append(a[count]*(1/(b[count] if b[count]!=0 else 0))
  2. b==0 is invalid. I do not know why. It is surely not what you want. Please post the code, and the error message.

3.More pythonic would be:

for count in range(len(a)):
        toappend=a[count]//b[count] #integer division
    except ZeroDivisionError:

Edited 3 Years Ago by slate: 2. point

This question has already been answered. Start a new discussion instead.