1

I have a Python list filled with instances of a class I defined.

I would like to create a new list with all the instances from the original list that meet a certain criterion in one of their attributes.

That is, for all the elements in list1, filled with instances of some class obj, I want all the elements for which obj.attrib == someValue.

I've done this using just a normal for loop, looping through and checking each object, but my list is extremely long and I was wondering if there was a faster/more concise way.

Thanks!

3 Answers 3

3

There's definitely a more concise way to do it, with a list comprehension:

filtered_list = [obj for obj in list1 if obj.attrib==someValue]

I don't know if you can go any faster though, because in the problem as you described you'll always have to check every object in the list somehow.

Sign up to request clarification or add additional context in comments.

Comments

1

You can perhaps use pandas series. Read your list into a pandas series your_list. Then you can filter by using the [] syntax and the .apply method:

def check_attrib(obj, value):
    return obj.attrib==value

new_list = your_list[your_list.apply(check_attrib)]

Remember the [] syntax filters a series by the boolean values of the series inside the brackets. For example:

spam = [1, 5, 3, 7]
eggs = [True, True, False, False]

Than spam[eggs] returns:

[1, 5]

This is a vector operation and in general should be more efficient than a loop.

Comments

1

For completeness, you could also use filter and a lambda expression:

filtered_lst1 = filter(lambda obj: obj.attrib==someValue, lst1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.