Skip to content
Advertisement

How do I reduce multiple nested if statements in Python?

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:

JavaScript

Is there a neat or efficient workaround for this snippet?

Please Advise

Advertisement

Answer

You can also write:

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement