1

I am quite new to Python (have a C++ background). I have a function in my Python code that returns an array of some objects (on which I don't have any control) like below:

def _get_object_array():
    object_array[]
    # Magically get array contents from somewhere
    # The objects have some fields like id, name etc.
    return object_array

Then in another function I call _get_object_array() to retrieve only the id's of the objects returned.

What I have is following:

id_array = []
id_array = [x.id for x in _get_object_array()] #<--

But I don't want the ids of all the objects in the returned array. Instead I only want to store the ids for array elements which meet some criteria (e.g. id is an even number?)

Is there a way I can do that in the same line marked with <-- like below (which btw is just a pseudo code)?

id_array = [if x.id % 2 == 0: x.id for x in _get_object_array()]

Thanks in advance.

/R

2 Answers 2

5

Yep: same words, you just got the syntax backwards.

id_array = [x.id for x in _get_object_array() if x.id % 2 == 0]

List comprehensions are amazing, and can do a lot more work than most people realise; have a read of the relevant PEP.

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

2 Comments

Also remember if you are going to iterate over the array a single time later, you can use () instead of [] to create a generator that calculates the values on the fly instead of all at once, it saves memory that way.
Yeah, that's also great for using any and all.
2

Yes, and you were very close:

id_array = [x.id for x in _get_object_array() if x.id % 2 == 0]

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.