0

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
0

5 Answers 5

2

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).

Sign up to request clarification or add additional context in comments.

Comments

2

try this:

X=[(i-C1)/C2 for i in X]

Comments

2

Note that although the following is possible it may not be recommended:

for i,v in enumerate(X):
  X[i]=(v-C1)/C2

3 Comments

People don't recommend editing a data structure while iterating through it, although I don't see the problem in this case.
@robert, you shouldn't add or remove elements while iterating. Replacing items is ok
This is the way to do it if you need to include other statements in the loop, or perhaps if the formula is more complicated
1

You can do

X = [(y - C1) / C2 for y in X]

This will not modify your list, but create a new list based on the change you wanted to do and assign it back to X.

Comments

1

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"

1 Comment

The slice assignment is a good way to save memory if you use a generator expression instead of a list comprehension X[:] = ((y - C1) / C2 for y in X)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.