Reputation: 3677
I have a list of objects, each of which has a list of things. I wish to create a list of the things held in all of the objects. Is there a more pythonic way of doing this?
class Holder(object):
def __init__(self, things):
self.things = things
holder_one= Holder([1, 2])
holder_two = Holder(['a', 'b'])
holders = [holder_one, holder_two]
all_things = []
for holder in holders:
for thing in holder.things:
all_things.append(thing)
print all_things
Upvotes: 0
Views: 50
Reputation: 81644
You could either:
Make Holder
inherit from list
then this becomes pretty trivial.
Use extend
instead of append
, which will save you an explicit loop:
all_things = []
for holder in holders:
all_things.extend(holder.things)
print all_things
Upvotes: 1