0

I am trying to divide values from two lists by each other, and I want to output a list with the quotients. The problem I am having is that all of the values are going through each other and dividing.

If I have two lists like this:

lst1 = [101, 2, 3]
lst2 = [69, 0, 0]

I want the output to look like this when I divide lst2[0]/lst1[0], lst2[1]/lst1[1], lst2[2]/lst1[2]:

output_lst = [0.6831683168316832, 0.0, 0.0]

My code looks like this, which gives me an output like this instead:

output_lst = [((x)/(y)) for x in lst2 for y in lst1]

print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

I've also tried this, which also gives me the same output:

for x in lst2:
   for x in lst1:
      output_lst = x/y
      print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

I'm trying to avoid doing each calculation individually and then putting it all into a list. How can I just divide the values in order, with no values being repeatedly divided?

Where am I going wrong in my code? Would appreciate any help - thanks.

  • 1
    By `for x in lst2 for y in lst1` you're doing an operation on every item in `list2` for every item in `lst1`. Just use `range(len(lst1))` assuming they're the same length, and access by index. Or `zip()`. – Random Davis Jul 07 '22 at 19:10

2 Answers2

2

This is a job for the zip function. Using the same order of elements...

output_lst = [x/y for x,y in zip(lst2, lst1)]

notovny
  • 131
  • 1
  • 4
1

You are really close with your first code sample. Just add zip into the mix and you are there.

lst1 = [101, 2, 3]
lst2 = [69, 0 ,0]

output = [x/y for x, y in zip(lst2, lst1) if y != 0]
print(f"{output}")
TBruce
  • 31
  • 1