[Tutor] interpreting error messages

Brian van den Broek bvande at po-box.mcgill.ca
Thu Oct 7 01:39:32 CEST 2004


Jacob S. said unto the world upon 2004-10-06 18:21:
> Hey,
> 
>     Just in case you're wondering, the examples you gave follow these
> ideas...

<SNIP>

>>>>def foo():
> 
>  pass
> 
> 
>>>>for x in foo:
> 
>  print x
> 
> 
> Traceback (most recent call last):
>   File "<pyshell#15>", line 1, in ?
>     for x in foo:
> TypeError: iteration over non-sequence
> 
> 
> This means that you are trying to loop through an object that absolutely
> cannot be expressed as a list. For example, lists can be turned into lists,
> tuples to lists, strings to lists, etc. Dictionaries, classes, functions,
> etc. cannot be turned into lists.
> 

<SNIP>

Not quite, I think. A dictionary isn't a list, true. But it can be 
iterated over:

 >>> my_dict = {1:100, 2:200, 3:299.99}
 >>> for i in my_dict:
... 	print i
... 	
1
2
3
 >>> for i in my_dict.keys():
... 	print i
... 	
1
2
3
 >>> print list(my_dict)
[1, 2, 3]
 >>>

The last shows that you can also "convert" a dictionary to a list. (The 
scare quotes because, unlike list((1,2,3)) (converting a tuple to a 
list), some real information is lost.

The point is, that you can iterate over any object that gives up a 
sequence when asked for one to iterate over. (And, now that my 
vocabulary to give the correct explanation is giving out, I will leave 
the interactive session paste to do the talking for me ;-)

Best,

Brian vdB



More information about the Tutor mailing list