ids = []
for object in objects:
ids += [object.id]
views:
262answers:
4You can use list comprehension
ids = [object.id for object in objects]
For you reference:
Both produce the same result. In many cases, List comprehension is a elegant and pythonic way to do the same thing, you have mentioned.
The standard (i.e “pythonic” a.k.a cleanest :) way is to use a list comprehension:
ids= [obj.id for obj in objects]
The above works for all Python versions ≥ 2.0.
Other ways (just FYI)
In Python 2, you can also do:
ids= map(lambda x: x.id, objects)
which should be the slowest method, or
# note: Python ≥ 2.4
import operator
ids= map(operator.attrgetter('id'), objects)
which might be the fastest method, although I assume the difference won't be that much; either way, the clarity of the list comprehension outweighs speed gains.
Should you want to use an alternative way in Python 3, you should enclose the map
call in a list
call:
ids= list(map(operator.attrgetter('id'), objects))
because the map
builtin returns a generator instead of a list in Python 3.
You don't need the operator module:
In [12]: class Bar(object):
def __init__(self, id_):
self.id = id_
In [15]: foo = [Bar(1) for _ in xrange(10000)]
In [16]: foobar = map(lambda bar: getattr(bar, 'id'), foo)
In [17]: len(foobar)
Out[17]: 10000
In [18]: foobar[:10]
Out[18]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]