Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing elements of a list using other lists in Python

I have multiple lists New, J,Pe_new. I want to replace the locations of New mentioned in J with corresponding values in Pe_new. For instance, for J[0]=1, I want to replace New[1] with Pe[0]=10. But getting an error. I present the expected output.

import numpy as np

New=[1.5, 2.9, 2.7, 6.3, 5.5]


J=[1, 2, 4]
Pe_new=[10, 20, 30]

for i in range(0,len(J)):
    New=New[J[i]]
print(New)

The error is

in <module>
    New=New[J[i]]

TypeError: 'float' object is not subscriptable

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1.5, 10, 20, 6.3, 30]

>Solution :

You can zip the indices and the new values to iterate through them together and assign to New with the value and at the index in each iteration:

for index, value in zip(J, Pe_new):
    New[index] = value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading