Extract list of attributes from list of objects in python

ListLoopsPython

List Problem Overview


I have an uniform list of objects in python:

class myClass(object):
    def __init__(self, attr):
        self.attr = attr
        self.other = None

objs = [myClass (i) for i in range(10)]

Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function (for plotting that data for example)

What is the pythonic way of doing it,

attr=[o.attr for o in objsm]

?

Maybe derive list and add a method to it, so I can use some idiom like

objs.getattribute("attr")

?

List Solutions


Solution 1 - List

attrs = [o.attr for o in objs] was the right code for making a list like the one you describe. Don't try to subclass list for this. Is there something you did not like about that snippet?

Solution 2 - List

You can also write:

attr=(o.attr for o in objsm)

This way you get a generator that conserves memory. For more benefits look at Generator Expressions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfranjesusView Question on Stackoverflow
Solution 1 - ListMike GrahamView Answer on Stackoverflow
Solution 2 - ListReto AebersoldView Answer on Stackoverflow