Versace
Versace

Reputation: 185

TypeError: 'int' object does not support item assignment - new to Python

Trying to do some some questions in a book yet I'm stuck with my arrays. I get this error:

count[i] = x
TypeError: 'int' object does not support item assignment

My code:

import pylab
count = 0

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

Basically I need to use a loop to store values which increase until they hit 300 in an array. I'm not sure why I'm getting that error.

I might have worded this poorly. I need to use a loop to make 6 values, from 200, 220, 240... to 300, and store them in an array.

Upvotes: 1

Views: 14686

Answers (4)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You don't need the while loop, you can use range with a start,stop,step:

count = []
for i in xrange (6):
    for x in  xrange(180,300,20):
        count.append(x)
        print count

Or use range with extend:

count = []
for i in xrange(6):
    count.extend(range(180,300,20))

Or simply:

 count range(180,300,20) * 6 `

Upvotes: 1

matcheek
matcheek

Reputation: 5147

Use dictionary

count = {}

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

count is an integer. Integers don't have indexes, only lists or tuples (or objects based on them) do.

You want to use a list, and then append values to it:

count = []
for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

Upvotes: 4

Kasravnd
Kasravnd

Reputation: 107287

You have defined count as an int number and as the error says ('int' object does not support item assignment) you need a list instead , :

count = []

and use append() function to append the numbers to your list :

for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

Upvotes: 1

Related Questions