Psionman
Psionman

Reputation: 3677

Create a list of items from object's items

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

Answers (1)

DeepSpace
DeepSpace

Reputation: 81644

You could either:

  1. Make Holder inherit from list then this becomes pretty trivial.

  2. 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

Related Questions