3

I'm working with a code snippet that iterates over an object list and filters out objects to perform a specific task. The for loop consists of multiple nested if statements (and I'll probably add more in the future).

Here's my code:

for obj in objects:
  if 'x' not in obj.name:
    if 'y' not in obj.name:
      if 'z' not in obj.name:
        if obj.length > 0:
          if obj.is_directory == True:
            
            # Do Something

Is there a neat or efficient workaround for this snippet?

Please Advise

1
  • common technique is inversing the condition and using early returns/break/continue. Commented May 5, 2022 at 7:00

2 Answers 2

5

You can also write:

for obj in objects:
   if not any(c in obj.name for c in 'xyz') and obj.length > 0 and obj.is_directory:
      # Do something

In case x, y and z are not single characters the solution remains the same. A string in Python is a sequence of characters, so you can substitute the 'xyz' string with the sequence (list) of words. You can put any iterable in there as well.

for obj in objects:
   if not any(w in obj.name for w in [word1, word2, word3]) and obj.length > 0 and obj.is_directory:
      # Do something
Sign up to request clarification or add additional context in comments.

2 Comments

The x, y, z in my actual case are words like word1, word_2, _word3 how do I use that in your answer?
@Luke I edited my answer with a short explanation.
2

You can put them all into one if statement with and between each condition:

for obj in objects:
    if ('x' no in obj.name) and ('y' not in obj.name) and ('z' not in obj.name)
    and (obj.length > 0) and (obj.is_directory):
        #Do Something

Note that it is not necessary to check if obj.is_directory == True, and it will evaluate to true itself if it is true.

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.