how can i check whether a variable is iterable in my code?

Terry Reedy tjreedy at udel.edu
Sat Sep 20 18:58:56 CEST 2008


satoru wrote:
> On Sep 20, 6:35 pm, Aidan <ai... at gmail.com> wrote:
>> 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__'

In 3.0, it does.  Such consistency is one of the advantages of 3.0.

In at least some 2.x's, str still uses the older __getitem__ iteration 
protocol.  I am not sure about other built-in sequences.




More information about the Python-list mailing list