0

I have a list or array (what is the correct term in python?) of objects. What is the most efficient way to get all objects matching a condition?

I could iterate over the list and check each element, but that doesn't seem very efficient.

objects = []
for object in list:
  if object.value == "123":
    objects.add(object)
mhawke
  • 84,695
  • 9
  • 117
  • 138
secador de pelo
  • 687
  • 5
  • 26

2 Answers2

6

This is the simplest way:

objects = [x for x in someList if x.value == 123]

If you're looking for a faster solution, you have to tell us more about your objects and how the source list is built. For example, if the property in question is unique among the objects, you can have better performance using dict instead of list. Another option is to keep the list sorted and use bisect instead of the linear search. Do note however, that these optimization efforts start making sense when the list grows really big, if you have less than ~500 elements, just use a comprehension and stop worrying.

georg
  • 211,518
  • 52
  • 313
  • 390
2

You can use filter

objects = filter(lambda i: i.value == '123', l)

Note to self
Apparently the "filter vs list comp" debate starts flame wars.

Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • How is this "the most efficient way"? – vaultah Oct 09 '14 at 12:26
  • It is one-line, Pythonic, and `O(N)`, if you know a more efficient way feel free to post your own answer ;) – Cory Kramer Oct 09 '14 at 12:27
  • The most efficient way possible with Python would be a native extension module searching in the list, but that's not a serious option for like 99.9999999 % of possible use cases. For these 99.99 % filter is the absolutely right thing to do. +1 – dom0 Oct 09 '14 at 12:29
  • 1
    It's 2 times slower than a list comprehension from @georg's answer. – vaultah Oct 09 '14 at 12:33