Find a more efficient way to code an If statement in python
<p>it's the second time I'm confronted to this kind of code : </p>

<pre><code>    if "associÃ©" in gender or "gÃ©rant" in gender or "prÃ©sident" in gender or "directeur" in gender:
    gen = "male"
elif "associÃ©e" in gender or "gÃ©rante" in gender or "prÃ©sidente" in gender or "directrice" in gender:
    gen = "female"
else:
    gen = "error"
</code></pre>

<p>I'd like to find a more efficient way to write this code because it looks really bad. </p>

<p>I personally like doing this with <a href="https://docs.python.org/2/library/sets.html#set-objects" rel="nofollow"><code>sets</code></a>. For example:</p>

<pre><code>opts = ["associÃ©", "gÃ©rant", "prÃ©sident", "directeur"]


if set(opts) &amp; set(gender):
...
</code></pre>

<p><code>&amp;</code> is used for the set intersection operation which returns a new <code>set</code>  with the items shared by the sets on either side of the <code>&amp;</code>. This will execute the <code>if</code> block only if there is overlap in <code>gender</code> and <code>opts</code>. You can repeat the process for your <code>elif</code> as well, creating a list of the possible options and checking for overlap between that list and <code>gender</code>. All together, you could do something like this:</p>

<pre><code>male_opts = ["associÃ©", "gÃ©rant", "prÃ©sident", "directeur"]
female_opts = ["associÃ©e", "gÃ©rante", "prÃ©sidente", "directrice"]

if set(male_opts) &amp; set(gender):
    gen = "male"
elif set(female_opts) &amp; set(gender):
    gen = "female"
else:
    gen = "error"
</code></pre>

<p>Also, as <strong>@Copperfield</strong> points out. You could increase efficiency even more by making the <code>*_opt</code> variables (and potentially even <code>gender</code> sets to begin with:</p>

<pre><code>male_opts = {"associÃ©", "gÃ©rant", "prÃ©sident", "directeur"}
female_opts = {"associÃ©e", "gÃ©rante", "prÃ©sidente", "directrice"}
gender = set(gender)

if male_opts &amp; gender:
...
</code></pre>

<h1>Edit:</h1>

<p>The code above assumes that <code>gender</code> is an iterable, but it seems from the comments that it is a string instead (e.g., <code>'associÃ© gÃ©rant'</code>. Although the accepted answer is better at this point, you could still use this solution by making <code>gender</code> a set of the words that make up the string:</p>

<pre><code>gender = set(gender.split())
</code></pre>

python if-statement