TypeError: 'int' object does not support item assignment in Python

Dung Do Tien Sep 21 2021 175

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have some lines of code, I am using range to help create a range an loop it to calculate temperature. Function as below:

p=range(0,600,10)
lenp=len(p)
rp=1.331
po=1000
T=280
Temp=(lenp)

for i in p:
    Temp[i]=T*(p[i]/po)**rp
print(Temp)

But I get an exception TypeError: 'int' object does not support item assignment  when I run code above.

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    Temp[i]=T*(p[i]/po)**rp
TypeError: 'int' object does not support item assignment

Temp[i]=T*(p[i]/po)**rp this line of code threw exception but I still don't understand how to fix it.

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • P

    Phúc Lê Khắc Sep 21 2021

    You can change your Temp variable to an array and using append() method. You can see the example below:

    p=range(0,600,10)
    lenp=len(p)
    rp=1.331
    po=1000
    T=280
    Temp=[]
    
    for i in p:
        Temp.append(T * (i / po) ** rp)
    print(Temp)

    #Output

    [0.0, 0.6097587362588845, 1.534012701571546, 2.6315184627336534, 3.8592230478248353, 5.193822543935866, 6.620295054763366, 8.127996774611885, 
    9.708917349644109, 11.356769502303612, 13.066462648800083, 14.833775272526449, 16.655139317014292, 18.527491950859595, 20.448169987831832, 
    22.41483246371504, 24.42540245383061, 26.47802242799972, 28.57101937110665, 30.702877102309788, 32.872214001964544, 35.07776486920176, 
    37.3183659818075, 39.592942671847254, 41.900498901414956, 44.240108445848236, 46.61090738159814, 49.01208764253601, 51.4428914584839, 
    53.902606527752205, 56.39056180465851, 58.906123805655454, 61.44869335544024, 64.01770270843991, 66.61261299223575, 69.23291192845473, 
    71.87811179390164, 74.54774759060129, 77.24137539824734, 79.95857088652872, 82.69892796809745, 85.4620575756807, 88.24758654913263, 
    91.05515662014778, 93.88442348398429, 96.73505594892305, 99.60673515536331, 102.4991538574568, 105.41201576104291, 108.34503491238597, 
    111.2979351328564, 114.27044949524785, 117.26231983790564, 120.27329631325838, 123.3031369677117, 126.35160735018283, 129.4184801468367, 
    132.5035348398312, 135.60655738809908, 138.7273399283865]
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close