99

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")

?

franjesus
  • 1,187
  • 1
  • 8
  • 8
  • 1
    See duplicate http://stackoverflow.com/q/677656/127465, esp. the answer with operator.attrgetter – ThomasH Oct 12 '10 at 08:20
  • Possible duplicate of [How to extract from a list of objects a list of specific attribute?](https://stackoverflow.com/questions/677656/how-to-extract-from-a-list-of-objects-a-list-of-specific-attribute) – Georgy Oct 26 '18 at 09:01

2 Answers2

102

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?

Mike Graham
  • 69,495
  • 14
  • 96
  • 129
  • 2
    Only that it's too verbose and I'm going to be using it often, so a shortcut would be handy. numpy's structured arrays arr['colname'] or recarrays arr.colname, already provide something similar, but in this case I'm using objects that hold named data (and some functions). – franjesus May 03 '10 at 17:48
  • If that is your intention, `getOattr= lambda l,a: [getattr(i,a) for i in l]` so that you can `getOattr(l,'id')` or`getOattr(l,'name')` . If you need more specific then `getIds= lambda l,a: [i.id for i in l]` so that you can `getIds(l)` – user2390183 Mar 04 '19 at 23:24
  • I wonder what is "better" from both answers.With round brackets `()` or with square brackets `[]`. ... The rest of the code is equal. Well, I understand that these are different ways of how it works internally. But as a Python newcomer I don't know if it doesn't matter, which way I should follow. – Beauty Jan 27 '21 at 09:25
  • @Beauty they do slightly different things, which might matter sometimes, for instance if you wanted to iterate over the result twice or reverse the result. – Mike Graham Jan 27 '21 at 19:21
96

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.

Reto Aebersold
  • 15,788
  • 4
  • 53
  • 71
  • would accessing a specific entry result of a O(n) operation?. e.g would accessing index = 100 of attr[100] will result the generator to run 100 steps? – Hanan Shteingart Jun 22 '19 at 18:01