DUNGHT13
DUNGHT13

Reputation: 41

for loop doesn't work with if else condition

So I want to do looping calculation over a list and it didn't work out. I want a new list with (1+log10(i)) inside:

    l = [115, 10, 2, 0]

    for i in l:
        l_1 = []
        if i == 0:
            l_1.append(i)
        else:
            l_1.append(1+np.log10(i))

    print(l_1)
    [0]

Upvotes: 2

Views: 76

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46839

or you could take full advantage of numpy:

import numpy as np

l = np.array((115, 10, 2, 0))
r = 1 + np.log10(np.where(l != 0, l, 0.1))
# [ 3.06069784  2.          1.30103     0.        ]

using numpy.where to weed out the 0 (and replacing it by 0.1 such that np.log10(x) = 1 which will result in 0 after the +1).

Upvotes: 1

whobbes
whobbes

Reputation: 140

The issue here is that for i in l gives you the values in i not the index so you only add one value, the last one.

here is a list comprehension that do what you want:

import numpy as np

l = [115, 10, 2, 0]
l_1 = [1+np.log10(i) if i !=0 else i for i in l]
print(l_1)

Upvotes: 1

Netwave
Netwave

Reputation: 42678

You are creating a new list in each loop pass, simple take it out:

l = [115, 10, 2, 0]
l_1 = []
for i in l:
    if i == 0:
        l_1.append(i)
    else:
        l_1.append(1+np.log10(i))

The pythonic way of doing this would be with a comprehension:

l_1 = [1+np.log10(i) if i != 0 else 0 for i in l]

Upvotes: 2

Related Questions