I'd like to edit some elements in python's list inside a loop. How can I make a proper loop for this? This code doesn't work:
for i in X:
i=(i-C1)/C2
Use a list comprehension:
X = [(i-C1)/C2 for i in X]
And a minor point, the Python Style Guide recommends using all lower case for your variable names, e.g.:
x = [(i-c1)/c2 for i in x]
Capital letters are usually used to start class names (and all-capitals denotes a constant).
Note that although the following is possible it may not be recommended:
for i,v in enumerate(X):
X[i]=(v-C1)/C2
using X[:] is better than X, as it allows splice assignment:
X[:] = [(y - C1) / C2 for y in X]
if you wanted to loop through, I would recommend using enumerate(X).
e.g.
for i,y in enumerate(X):
X[i] = (y - C1) / C2
Here i is assigned the position in the array (i = 0..len(X)-1) and y is the value of X[i].
look up enumerate if you're interested.
Of course you must be careful if you edit a list (or any data structure) while iterating through it in case you change values before they have been iterated. e.g:
x = [1,2,3]
for i,y in enumerate(x):
x[-1] = 99
print(i,y)
>>>
0 1
1 2
2 99
notice you get "2 99" instead of "2 3"
X[:] = ((y - C1) / C2 for y in X)