Madhu Oruganti
Madhu Oruganti

Reputation: 13

How to add number to list in for loop?

Here, H is a list of integers.
As per the condition in a for loop, I want to add/subtract numbers to the list.

for i in range(len(H)):
    if H[i] > 43:
        d.append(int(int(H[i]) - int(33)))
        M.append(OVF(H[i]))
        #print H
    elif (H[i]) < -43:
        d.append(H[i] + 33)
        M.append(OVF(H[i]))         
    else:
        d.append(H)

I am getting error at d.append(int(int(H[i]) - int(33))).

Please help, I am new to Python. The error I'm receiving is:

TypeError: int() argument must be a string or a number, not 'list'.

Upvotes: 0

Views: 6693

Answers (1)

Michael H.
Michael H.

Reputation: 3483

You wrote yourself that H[i] is a list and the error tells you that int() doesn't work with that kind of input, so I guess the error occurs when you call int(H[i]).
You can verify this with

>>> int([1., 2., 3.])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
>>> list(int(k) for k in [1., 2., 3.])
[1, 2, 3]

I guess you were expecting the output [1, 2, 3] with the call of int([1., 2., 3.]) in the above example as you say you're new to Python. I think what you want instead is

d.append([int(h)-33 for h in H[i]])

example:

>>> d = []
>>> d.append([int(h)-33 for h in [1., 2., 3.]])
>>> d
[[-32, -31, -30]]

Upvotes: 2

Related Questions