Reputation: 21
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
Reputation: 375
for i in range(len(your_list)):
if your_list[i] < 0:
your_list[i] += 1.5
print(your_list)
Upvotes: 0
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
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
Reputation: 106648
You can use modulo:
for i, n in enumerate(y):
if n < 0:
y[i] %= 1.5
Upvotes: 1
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