interating over single element array
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Jun 8 11:36:26 EDT 2007
In <4Beai.13210$5j1.6184 at newssvr21.news.prodigy.net>, T. Crane wrote:
> Can someone please explain to me why I can't do something like this:
>
> a = 1
>
> for value in a:
> print str(value)
>
> If I run this I get the error:
>
> 'int' object is not iterable
Well the message explains why you can't do this. `a` is bound to an
integer and integers are not iterable.
> Obivously this is an absurd example that I would never do, but in my
> application the length of 'a' can be anything greater than 0, and I want to
> be able to handle cases when 'a' has only one element without coding a
> special case just in the event that len(a) = 1.
``len(a)`` wouldn't work either because integers have no "length":
In [16]: a = 1
In [17]: len(a)
---------------------------------------------------------------------------
exceptions.TypeError Traceback (most recent call last)
/home/new/<ipython console>
TypeError: len() of unsized object
> any suggestions are appreciated,
Yes, don't try iterating over objects that are not iterable. ;-)
What you *can* do is iterating over lists, tuples or other iterables with
just one element in them. Try ``a = [1]``.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list