Skip to content Skip to sidebar Skip to footer

Python Iteration Of List Of Objects "not Iterable"

New to Python, but I have been researching this for a couple hours. Forgive me if I missed something obvious. I have a class called LineItem, which has an attribute _lineItems, a l

Solution 1:

defprint_line_item(LineItems):
    count = 1for a in LineItems:
        print count, ' ', a.description, ' (', a.amount, ')'if a._lineItems != []:
            for b in a._lineItems:
                print count, '.', print_line_item(b),
        count+=1

It might be correct version, not tested.

defprint_line_item(LineItems, precedingNumber='1'):
    count = 1for a in LineItems:
        print precedingNumber, '.', count, ' ', a.description, ' (', a.amount, ')'
        print_line_item(a._lineItems, precedingNumber + '.' + count),
        count+=1

Solution 2:

It makes sense you're getting a not-iterable message--you're essentially recursing into print_line_item for each item in a list--and sooner or later, you'll hit something in a list that isn't iterable itself--and you just go on and call print_line_item() on it, which will try to iterate over it.

If you want to ask "is this item a list?" you could use isinstance(some-object, list). Or, if you want to allow for other iterable-but-not-list-things, you can use if isinstance(some-object, collections.Iterable) (you'll have to import collections).

Post a Comment for "Python Iteration Of List Of Objects "not Iterable""