Why doesn't this list comprehension do what I expect it to do?

Posted by Az on Stack Overflow See other posts from Stack Overflow or by Az
Published on 2010-05-30T19:53:08Z Indexed on 2010/05/30 20:02 UTC
Read the original article Hit count: 260

The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110.

Thus:

for project in projects.itervalues():
# The projects dictionary is mapped to the Project class
    if project.invalid:
    # Where invalid is a Bool parameter in the Project class
     project_keys.remove(project.proj_id)  

print project_keys

This will return a list of integers (which are project id's) as such:

[101, 102, 103, 104, 105, 106, 107]

Sweet.

Now, I wanted it try the same thing using a list comprehension.

project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid  

print project_keys

This returns:

[None, None, None]

So I'm populating a list with the same number as the removed elements but they're Nones?

Can someone point out what I'm doing wrong?

Additionally, why would I use a list comprehension over the for-if block at the top? Conciseness? Looks nicer?

© Stack Overflow or respective owner

Related posts about python

Related posts about list-comprehension