Re: how can i check whether a variable is iterable in my code?
On Sep 20, 8:54 pm, satoru <torainLi...@gm ail.comwrote:
On Sep 20, 6:35 pm, Aidan <ai...@gmail.co mwrote:
>
satoru wrote:
hi, all
i want to check if a variable is iterable like a list, how can i
implement this?
>
this would be one way, though I'm sure others exist:
>
if hasattr(yourVar , '__iter__'):
# do stuff
>
thank you,but this will miss out sequences like string just because it
doesn't have an attribute named '__iter__'
str objects have a __getitem__ attribute, as do other built-in
sequence types: unicode, xrange, buffer.
AFAIK if an object has no __iter__ but has a __getitem__, iter(obj)
will create an iterator that calls obj.__getitem__ (0),
obj.__getitem__ (1), etc until IndexError is raised.
Comment