Python error type error: ‘range’ object does not support item assignment, solution

1. Examples are as follows:

from math import sqrt
if __name__ == '__main__':
    N = 100
    a = range(0,N)
    for i in range(2,int(sqrt(N))):
        for j in range(i + 1,N):
            if (a[i] != 0) and (a[j] != 0):
                if a[j] % a[i] == 0:
                        a[j]= 0

    for i in range(2,N):
        if a[i] != 0:
            print ("%5d" % a[i])
            if (i - 2) % 10 == 0:
                print         

Error after execution: typeerror: ‘range’ object does not support item assignment

2. The reasons for the error are as follows:

Try to use range()
to create an integer list (leading to “typeerror: ‘range’ object does not support item assignment”). Sometimes you want to get an ordered integer list, so range() seems to be a good way to generate this list. However, you need to remember that range () returns the “range object” instead of the actual list value.

3. Solutions:

Just change the code of the above example: a = range (0, n) to a = list (range (0, n))!

Read More: