[Tutor] TypeError: object doesn't support item assignment [ Trying to learn how to enter value in array ]
Brian van den Broek
broek at cc.umanitoba.ca
Mon Jan 2 10:55:58 CET 2006
John Joseph said unto the world upon 02/01/06 02:48 AM:
> Hi All
> I am trying to write a program in which I enter
> the no of students and then for the students I enter
> the marks and later on Display the marks
> The script which I wrote is given below , when I run
> the program I get error
> “TypeError: object doesn't support item assignment “ ,
> my aim in doing this program is to learn how to enter
> values in a array , please advice how can I avoid
> this error
> Guidance requested
> Thanks
> Joseph
>
> ##################################################################
> # This program is to learn how u enter entry to the
> array
> # And how u print it ,
>
>
> print " \nFirst Enter the No of Students ... "
> print "\n Then No of marks "
>
> # defining empty array a
> a = ()
> # defining i
> i = 0
>
> # n is the No of students which I have to enter the
> marks
> n = int(raw_input("Enter the no: of students : \n"))
>
>
> # m is the Marks of the students which I have to enter
> while i < n:
> m = int(raw_input("Enter the Marks for the
> students : \n"))
> a[i] = m
> print "Marks are ", m
> i = i+1
>
> #print "Array Marks ", a[i]
Hi John,
the whole traceback is helpful, as it (tries to) show the line that
made Python choke:
Traceback (most recent call last):
File "/home/tempos/foo.py", line 16, in -toplevel-
a[i] = m
TypeError: object does not support item assignment
See how that shows us that it is the a[i] = m that is the problem?
See if this helps work it out:
>>> a_tuple = ()
>>> a_tuple[0] = "Won't work, as tuples are immutable"
Traceback (most recent call last):
File "<pyshell#7>", line 1, in -toplevel-
a_tuple[0] = "Won't work, as tuples are immutable"
TypeError: object does not support item assignment
>>> a_list = []
>>> a_list[0] = "Won't work, different reason"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in -toplevel-
a_list[0] = "Won't work, different reason"
IndexError: list assignment index out of range
>>> a_preloaded_list = [None]
>>> a_preloaded_list[0] = "Will work, but not the best way generally"
>>> a_preloaded_list
['Will work, but not the best way generally']
>>>
It doesn't seem that you are aiming to correlate marks with students
yet, but just want a list of marks. In that case:
>>> marks = [] # 'a' is not a helpful name :-)
>>> mark = raw_input("What mark?")
What mark?17
>>> marks.append(mark)
>>> mark = raw_input("What mark?")
What mark?42
>>> marks.append(mark)
>>> marks
['17', '42']
>>>
HTH,
Brian vdB
More information about the Tutor
mailing list