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):

    c.append(a[count]*(1/b[count])

    if b ==0:  #invalid syntax error
        c.append(d)

    count = count + 1

print(c)

Recommended Answers

All 3 Replies

  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)):
    try:
        toappend=a[count]//b[count] #integer division
    except ZeroDivisionError:
        toappend=0
    c.append(toappend)
 c=[x / y if y else 0 for x, y in zip(a, b)]  

Thank you soooo much slate and pyTony :)
It's fixed now and working

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.