0

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)

5 Answers5

2

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
  • what if I want to apply a fairly complex function (like a*i+b*i^2) to the y[i] that's smaller than 0, and the 'a' decreases by half every time it's used? (I was reading about nested loops, but I haven't learned them in class yet...) – vincent yip Oct 08 '19 at 03:54
  • Sorry, not sure of what you need but to decrease a number by half at each iteration, you can use: "a/=2" inside a loop. With this, each time you loop, a is divided by 2 – Thomas Zwetyenga Oct 08 '19 at 04:00
1

You can use modulo:

for i, n in enumerate(y):
    if n < 0:
        y[i] %= 1.5
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • what if I want to apply a fairly complex function (like a*i+b*i^2) to the y[i] that's smaller than 0, and the 'a' decreases by half every time it's used? (I was reading about nested loops, but I haven't learned them in class yet...) – vincent yip Oct 08 '19 at 03:53
0

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)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • what if I want to apply a fairly complex function (like a*i+b*i^2) to the y[i] that's smaller than 0, and the 'a' decreases by half every time it's used? (I was reading about nested loops, but I haven't learned them in class yet...) – vincent yip Oct 08 '19 at 03:53
  • In that case I would declare `a = some_value` before the nested `while` loop, and then inside the nested loop just decrease it every time. This way, every iteration of the `for` loop it gets reset. Nested loops shouldn't need explanation - they work exactly like you'd expect. – Green Cloak Guy Oct 08 '19 at 04:22
0

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]
0
for i in range(len(your_list)):
    if your_list[i] < 0:
    your_list[i] += 1.5
print(your_list)
Z. Cajurao
  • 357
  • 2
  • 12
  • and if you want to do the way you did with foreach for i in your_list: if i < 0: your_list[your_list.index(i)] += 1.5 print(your_list) – Z. Cajurao Oct 08 '19 at 06:03