Replacing elements of a list using other lists in Python

Question:

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

[1.5, 10, 20, 6.3, 30]
Asked By: rajunarlikar123

||

Answers:

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
Answered By: blhsing

One way to do it is to use zip for iterating on both list simultaneously and performing your substituition.

for index,new_item in zip(J,Pe_new):
    New[index]=new_item
Answered By: Karen

The error makes complete sense as in the for loop you are trying to access an element of the New list by indexing it with a value from J i.e. New[J[i]], which is not a valid operation since New is a list of floats and you cannot index a float.

You should do the following:

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[J[i]]=Pe_new[i]
    
print(New)
Answered By: Sunderam Dubey
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.