vincent yip
vincent yip

Reputation: 21

Editing list using for loop

I want to change all the number in this list so that it will add 1.5 to anything that smaller than 0 until they are larger than 0, however, I don't understand why it would produce a very strange output ([1, 1, 1, 1, -3.5, -2.5, -4, -5, 0.5])


for i in y:
    if i<0:
        y[i] = i+1.5

print (y)

Upvotes: 0

Views: 63

Answers (5)

Z. Cajurao
Z. Cajurao

Reputation: 375

for i in range(len(your_list)):
    if your_list[i] < 0:
    your_list[i] += 1.5
print(your_list)

Upvotes: 0

Harryzzz
Harryzzz

Reputation: 11

Here is another solution using this method:

>>> x = [1, 1, 1, 1, -3.5, -2.5, -4, -5, -0.5]
>>> x = [i if i>0 else ((i%-1.5)+1.5) for i in x]
>>> print(x)
[1, 1, 1, 1, 1.0, 0.5, 0.5, 1.0, 1.0]

Upvotes: 0

Thomas Zwetyenga
Thomas Zwetyenga

Reputation: 86

You were mixing the indexes and elements of the list. And you needed a while instead of the "if" to keep going until you reach the wanted number.

Try something like this:

for i in range(len(y)):
    while y[i] < 0:
        y[i]+=1.5

Upvotes: 2

blhsing
blhsing

Reputation: 106648

You can use modulo:

for i, n in enumerate(y):
    if n < 0:
        y[i] %= 1.5

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Python iterates by value, by default. To iterate by index, you have to make a list of indices and iterate through that. You do this with the built-in range():

for i in range(len(y)):
    while y[i] < 0:
        y[i] += 1.5
print(y)

Upvotes: 0

Related Questions