TypeError: unsupported operand type(s) for /: 'float' and 'list': how can i split a lista with a float?

Question:

I’m putting together a code in which I take the percentage of the numbers from the npp_pls list and I want to divide the result obtained with the numbers from the mass_seed list but this error is appearing

TypeError: unsupported operand type(s) for /: ‘float’ and ‘list’

my code is as follows:

npp_pls = [10, 80, 5]
mass_seed = [0.1, 1.0, 3.0] #atributo variante 

for npp_rep in npp_pls:  
    npp_rep = npp_rep *0.1 

    print(npp_rep)



new_results = (npp_rep) / (mass_seed)
print(new_results)
Asked By: bruna soica

||

Answers:

You can use zip to iterate over both lists at the same time and do your calculations like this:

npp_pls = [10, 80, 5]
mass_seed = [0.1, 1.0, 3.0] #atributo variante 

result = [npp_rep * 0.1 / ms for npp_rep, ms in zip(npp_pls, mass_seed)]

EDIT:
Your error occurs because you are trying to divide a float npp_rep by a list mass_seed. Instead you probably want to divide npp_rep by the corresponding value in mass_seed

Answered By: bitflip

new_results = (npp_rep) / (mass_seed) part on runtime will be like new_results = 5 / [0.1, 1.0, 3.0], that is not supported.

So you can reach the result doing something like this:

new_results = [x / y for x, y in zip(npp_pls, mass_seed)]

Also i should mention that your for loop doesn’t cause any changes and just do some multiply and doesn’t save them anywhere, you can do this instead of your for loop:

npp_pls = [npp_rep * 0.1 for npp_rep in npp_pls]
Answered By: Amrez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.