list comprehension question

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed May 6 03:52:24 CEST 2009


On Tue, 05 May 2009 13:43:32 -0400, J. Cliff Dyer wrote:

> On Fri, 2009-05-01 at 13:00 -0400, John Posner wrote:
>> Shane Geiger wrote:
>> >    if type(el) == list or type(el) is tuple:
>> A tiny improvement:
>> 
>>         if type(el) in (list, tuple):
>> 
>> 
> Another alternative, which might be useful in some cases:
> 
>           if hasattr(el, '__iter__'):
> 
> This covers all iterables, not just lists and tuples.

Except for the ones that it doesn't cover, like strings:

>>> hasattr('abcd', '__iter__')
False
>>> list(iter('abcd'))
['a', 'b', 'c', 'd']


And classes that follow the sequence protocol:


>>> class Spam:
...     def __getitem__(self, index):
...             if 0 <= index < 5:
...                     return "spam"
...             raise IndexError
...
>>> hasattr(Spam(), '__iter__')
False
>>> list(iter(Spam()))
['spam', 'spam', 'spam', 'spam', 'spam']




-- 
Steven



More information about the Python-list mailing list