Anto Robich - 1 year ago 54

Python Question

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

x=np.linspace(0.0,4.0,100)

y1=x

for i in range(100):

y2[i]=1.5*(1-exp(-x[i]))

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):
y2.append(1.5*(1-exp(-x[i])))
```