15

I've got an list of objects in Python, and they each have an id property. I want to get a list of those IDs.

In C# I'd write

myObjects.Select(obj => obj.id);

How would I do this in Python?

mpen
  • 272,448
  • 266
  • 850
  • 1,236

5 Answers5

21

Check out the section on "List Comprehension" here: http://docs.python.org/tutorial/datastructures.html

If your starting list is called original_list and your new list is called id_list, you could do something like this:

id_list = [x.id for x in original_list]
Brent Writes Code
  • 19,075
  • 7
  • 52
  • 56
14
[obj.id for obj in myObjects]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

If it's a big list and you only need to process the ids once then there are also generator expressions.

ids = (obj.id for obj in my_objects)

for id in ids:
    do_something(id)

A generator expression doesn't support random access but will get you each id on demand and so avoids building a list all at once. generator expressions are to xrange as list comprehensions are to range.

One more caveat with generator expressions is that it can only be accessed for as long as any resource within it is still open. For example, the following code will fail.

with open(filename) as f:
    lines = (line for line in f)

# f is now closed
for line in lines:
    print line

The equivalent list comprehension would work in this case.

aaronasterling
  • 68,820
  • 20
  • 127
  • 125
4

If you want a direct equivalent of C# select in Python, at the cost of using a third-party library, you could use the asq package which provides a LINQ-for-objects inspired implementation over Python iterables. Using asq the C# code in your question would become:

from asq.initiators import query
query(myObjects).select(lambda obj: obj.id)

or, combined with another feature of asq:

from asq.selectors import a_
query(myObjects).select(a_("id"))
Rob Smallshire
  • 1,450
  • 1
  • 15
  • 22
1

Nobody in their right mind would do this the following way, but here it is in case it comes in handy in a more complex example

import operator
map(operator.attrgetter("id"), myObjects)
Katriel
  • 120,462
  • 19
  • 136
  • 170