user1190294
user1190294

Reputation:

List loop in python

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

Upvotes: 0

Views: 6767

Answers (5)

Rusty Rob
Rusty Rob

Reputation: 17213

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"

Upvotes: 1

Dan D.
Dan D.

Reputation: 74675

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

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

Upvotes: 2

David Webb
David Webb

Reputation: 193814

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

Upvotes: 2

MByD
MByD

Reputation: 137432

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.

Upvotes: 1

fakedrake
fakedrake

Reputation: 6866

try this:

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

Upvotes: 2

Related Questions