0

I am having the following python block where i want to check if a change doesnt exist in invalid_change and changes_not_in_manifest lists,the problem I am facing is as soon as the try loop is entered and checked for invalid_change.index(change) it goes to except,how do I check if a change is not present in both "invalid_change" and "changes_not_in_manifest" lists?

try: # check if invalid change is present
  invalid_change.index(change)
  changes_not_in_manifest.index(change)
  print "invalid list"
  ifvalid = False
  break
except:
  print "except"
  pass
python.beginner
  • 365
  • 3
  • 6
  • 12

1 Answers1

2

Normally this kind of test is done using the in keyword:

if change not in invalid_change and change not in changes_not_in_manifest:
    print "invalid list"

However, I think you are overlooking a good use case for sets. I have written a pretty detailed breakdown of a problem similar to this in this answer.

Basically, you would write a set comprehension like:

invalid_changes = {c for c in changes if c not in invalid_change or c not in manifest}

which you would later check using:

if change in invalid_changes:
    # do something
Community
  • 1
  • 1
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
  • I actually want to try using the try except block as shown in my query....can we modify the same?i have some constraints..i cannot move to the code suggestions you made – python.beginner Apr 17 '14 at 00:12
  • I'm not sure at all what your try/except block is supposed to do. You used the `index` method to test for membership which will throw a `ValueError` if its argument is not in the list. This is caught by your blanket `except` statement. Yet, in your question, you say you dislike that it jumps directly to the except block (i.e. that you catch that `ValueError` or anything else that crops up). – Two-Bit Alchemist Apr 17 '14 at 00:21
  • Note also that the `in` keyword is optimized for these tests. Using `index` to test for membership is always going to be slower. – Two-Bit Alchemist Apr 17 '14 at 00:22