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

How to replace all elements of a list using a for loop

Question
https://i.stack.imgur.com/CbX7L.png

The question here asks to make two lists/arrays in python and fill it with 0s initially and then occupy them with the relevant values.

import numpy as np
x = []
y = []

for i in range (0,101):
    x.append(0)
    y.append(0)

xx = np.linspace(1,10,101)
print(xx)

for a in range (len(y)):
    for j in xx:
        fx = np.log(j)
        y[a] = fx

for b in range (len(x)):
    for k in xx:
        x[b] = k

print(x)
print(" ")
print(y)

I used a nested for loop to traverse through the values in the xx list and used the log function and stored the values in a variable and then replace the 0s in the (y)list with the function values over each iteration. Same thing with the x list but just replace the 0s with the value of the variable which is used in the function respectively.
However the output I keep getting is not right and I can’t get what is going wrong within the loops. The output should show the values of x in the first list and the values of f(x) in the second list however it only shows the value of the last x in the range as well as the value of the last f(x) in the range.

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

Output
enter image description here

>Solution :

I’m guessing you are supposed to use linspace, and enumerate:

import numpy as np
size = 101
x = np.zeros(size)
y = np.zeros(size)

for i, n in enumerate(np.linspace(1,10,size)):
    x[i] = n
    y[i] = np.log(n)
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