Anto Robich Anto Robich - 1 year ago 169
Python Question

Error: 'float' object does not support item assignment

I'm programming in python and I don't understand what i'm doing wrong:

import numpy as np
import matplotlib.pyplot as plt
from math import exp
for i in range(100):


This last line gives me an error that says: float object does not support item assigment. I don't understand how y2 can be considered a float object since it is a list in which every element is calculated with 1.5*(1-exp(-x[i])).

Answer Source

As Jean-Fran├žois Fabre and Barmar have noted, you get this message only if you have y2 already assigned to a float. IN any case, you'll need to build the list one way or another.

Using the numpy array facilities (credit to John1024):

y2 = 1.5*(1-np.exp(-x))

Using a list comprehension:

y2 = [ 1.5*(1-exp(-x[i])) for i in range(100) ]

If these are more advanced than you want to use, you can initialize y2 and build it in your loop:

y2 = []
for i in range(100):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download