1

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.

1
  • 7
    count is an integer, not a list. You need to make count = [], and to add things to a list, you use .append Commented Jan 6, 2015 at 16:13

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Doing that, it tells me:count[i] = x IndexError: list assignment index out of range
@Versace yes , as you initial your list empty it raise index error , you need to use append function
1

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 `

Comments

0

Use dictionary

count = {}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.