Skip to content Skip to sidebar Skip to footer

Iterating Over List Or Single Element In Python

I would like to iterate over the outputs of an unknown function. Unfortunately I do not know whether the function returns a single item or a tuple. This must be a standard problem

Solution 1:

The most general solution to this problem is to use isinstance with the abstract base class collections.Iterable.

import collections

defget_iterable(x):
    ifisinstance(x, collections.Iterable):
        return x
    else:
        return (x,)

You might also want to test for basestring as well, as Kindall suggests.

    if isinstance(x, collections.Iterable) and not isinstance(x, basestring):

Now some people might think, as I once did, "isn't isinstanceconsidered harmful? Doesn't it lock you into using one kind of type? Wouldn't using hasattr(x, '__iter__') be better?"

The answer is: not when it comes to abstract base classes. In fact, you can define your own class with an __iter__ method and it will be recognized as an instance of collections.Iterable, even if you do not subclasscollections.Iterable. This works because collections.Iterable defines a __subclasshook__ that determines whether a type passed to it is an Iterable by whatever definition it implements.

>>>classMyIter(object):...def__iter__(self):...returniter(range(10))...>>>i = MyIter()>>>isinstance(i, collections.Iterable)
True
>>>collections.Iterable.__subclasshook__(type(i))
True

Solution 2:

It's not particularly elegant to include the code everywhere you need it. So write a function that does the massaging. Here's a suggestion I came up with for a similar previous question. It special-cases strings (which would usually be iterable) as single items, which is what I find I usually want.

def iterfy(iterable):
    if isinstance(iterable, basestring):
        iterable = [iterable]
    try:
        iter(iterable)
    except TypeError:
        iterable = [iterable]
    returniterable

Usage:

foriteminiterfy(unknownfunction()):
     # do something

Update Here's a generator version that uses the new-ish (Python 3.3) yield from statement.

def iterfy(iterable):
    if isinstance(iterable, str):
        yielditerableelse:
        try:
            # need "iter()" here to force TypeError on non-iterable# as e.g. "yield from 1" doesn't throw until "next()"yieldfrom iter(iterable)
        except TypeError:
            yielditerable

Solution 3:

Perhaps better to use collections.Iterable to find out whether the output is an iterable or not.

import collections

x = UnknownFunction()
ifnotisinstance(x, collections.Iterable): x = [x]

for ii in x:
    #do stuff

This will work if type of x is either of these - list, tuple, dict, str, any class derived from these.

Solution 4:

You'll want to do the following:

iterator = (x,) ifnotisinstance(x, (tuple, list)) else x

then

foriiniterator:
    #dostuff

Solution 5:

You could also try using the operator.isSequenceType function

importoperator
x = unknown_function()
ifnotoperator.isSequenceType(x) andnotisinstance(x, basestring):
    x = (x,)
for item in x:
    do_something(item)

Post a Comment for "Iterating Over List Or Single Element In Python"