Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Test Multiple Variables Against a Value in Python?

#1
How to Test Multiple Variables Against a Value in Python?

<div><p class="has-luminous-vivid-amber-background-color has-background">To test multiple variables <code>x</code>, <code>y</code>, <code>z</code> against a <code>value</code> in Python, use the expression <code>value in {x, y, z}</code>. Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value. </p>
<p>Here’s the code:</p>
<p> <iframe src="https://trinket.io/embed/python/ca2260e046" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="500" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Add a fourth variable and run the modified code!</em></p>
<hr class="wp-block-separator"/>
<p>In this article, you’ll learn about an interesting problem in programming. Interesting because a quick glance could give us a feeling of this problem being simple. However, diving into it can help us learn some fundamentals about Boolean operators and some data types in a way we might not have thought about earlier. In fact, you could find yourself in this situation if you’re a beginner. We will try and explore some solutions to this problem using Python taking into consideration three approaches.</p>
<ul>
<li>The Incorrect Approach</li>
<li>The Correct Approach</li>
<li>The Best Approach</li>
</ul>
<p>Let’s see some code walkthrough to understand it.</p>
<h2>Doing It The Wrong Way — The Incorrect Approach</h2>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-23.png" alt="" class="wp-image-10019" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-23.png 468w, https://blog.finxter.com/wp-content/uplo...00x258.png 300w" sizes="(max-width: 468px) 100vw, 468px" /></figure>
<p>Let’s consider the above lines of code. We have three variables, x = 0, y = 1 and z = 3 and want to <a href="https://blog.finxter.com/print-a-list-of-list-in-python/" target="_blank" rel="noreferrer noopener" title="How to Print a List of List in Python?">print a list</a>, “list1” as output which checks at line 9, 11, 13 and 15 respectively, if either of x, y or z equals to 0, 1, 2, or 3 and append to our output list – list1, the values, c, d, e, and f based on the output condition.</p>
<p>Pause for a moment, and observe. What should be the output for the above lines of code? Now run the above code snippet. If you were expecting the output – [‘c’, ‘d’, ‘f’], read along carefully.</p>
<p>Let’s find out what is happening with our code. To understand it clearly, we must appreciate a few things first. The logical operators in <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener" title="Python Programming Tutorial [+Cheat Sheets]">Python </a>do not work<strong>&nbsp;</strong>in a way you would expect them to work in English. For instance, let us look at line 9 of the code snippet.</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-24.png" alt="" class="wp-image-10020"/></figure>
<p>From Python documentation (<a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="noreferrer noopener">Boolean operations</a>), the expression “x or y” first evaluates x<strong>.</strong>&nbsp;If x is true, its value is returned. Otherwise, y is evaluated, and the resulting value is returned.</p>
<p>The second point to note here is about&nbsp;<a target="_blank" href="https://docs.python.org/3/reference/expressions.html#operator-summary" rel="noreferrer noopener">operator precedence</a>. The “or” operator has lower precedence than “==” operator, and hence equality is evaluated first.</p>
<p>The line number 9 returns “1” (True) as output. So line number 9 and 10 simplifies to:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-25.png" alt="" class="wp-image-10021"/></figure>
<p>Similarly, line 11, 13, and 15 each return 1 as output and hence (therefore) “d”, “e” and “f” gets appended to the list. Below code snippet shows the output for all the conditions individually:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-26.png" alt="" class="wp-image-10022"/></figure>
<p>Operations and built-in functions that have a Boolean result always return 0 or False for a false and 1 or True for true, unless otherwise stated. Thus our final output to code snippet in fig1 returns [“c”, “d”, “e”, “f”]</p>
<h2>Doing It The Right Way — The Correct Approach</h2>
<p>Now we build upon our mistakes above and look at a solution that should give us the expected output. Let’s modify the above code snippet a little and see how it changes the expected output:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-27.png" alt="" class="wp-image-10023" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-27.png 478w, https://blog.finxter.com/wp-content/uplo...00x258.png 300w" sizes="(max-width: 478px) 100vw, 478px" /></figure>
<p>The difference is evident here as we use the statement “x == 0 or y == 0 or z == 0” instead of “x or y or z == 0”. In this case, each variable here i.e. x, y, z are checked for equivalence one after the other and if the condition satisfies, the corresponding alphabet i.e c, d, e, f is appended to our list 1 respectively. Run the above code and check the output.</p>
<h2>Doing It The Better Way: A Better Approach</h2>
<p>With Python, we get myriads of <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">collection</a>/sequence data types and some in-built keywords that we can work with. The original idea of different collection/sequence data types and the keywords available for our use is to simplify how we can create a collection/sequence of data and access them based on the problem statement we are dealing with. We will check two data structures – Tuples and <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Sets – with Harry Potter Examples">Sets</a>, which bring in a good use case for the scenario that we are dealing with.</p>
<p>The “<a href="https://blog.finxter.com/check-if-a-list-contains-an-element/" target="_blank" rel="noreferrer noopener" title="The Most Pythonic Way to Check If a List Contains an Element">in</a>” keyword can be used along with sequences like lists, sets, and tuples. It returns True or False based on whether the operand on the left is found or not in the sequence. Let’s check out the code snippet below:</p>
<h3>Using Tuples to Do it Better:</h3>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-28.png" alt="" class="wp-image-10024" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-28.png 589w, https://blog.finxter.com/wp-content/uplo...00x210.png 300w" sizes="(max-width: 589px) 100vw, 589px" /></figure>
<p>In this case, we define variables x, y, and z and then check for the specific value <a href="https://blog.finxter.com/how-to-test-multiple-variables-against-a-value-in-python/" target="_blank" rel="noreferrer noopener" title="How to Test Multiple Variables Against a Value in Python?">membership </a>with tuples in the above case. Hence, on line 9 we check, 0 to be in the tuple (0, 1, 3), which is a membership check, and if the condition is True, we append alphabet “c” to our list1. Then the membership check is done for values 1, 2, and 3, respectively, and based on whether the condition is True or False, the respective alphabet values of “c”, “d”, “e”, “f” are appended to our list1.</p>
<p>To clarify further, on line 9 we get the output as True and hence “c” is appended to list1 whereas, on line 13, where we check for membership of 2 in the tuple (0, 1, 3), the condition is False and hence “e” is not appended to list1.</p>
<h3>Using Sets to Do it Better:</h3>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/image-29.png" alt="" class="wp-image-10025" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-29.png 569w, https://blog.finxter.com/wp-content/uplo...00x209.png 300w" sizes="(max-width: 569px) 100vw, 569px" /></figure>
<p>Here’s the code for easier copy&amp;pasting:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 0
y = 1
z = 3 list1 = [] if 0 in {x, y, z}: list1.append('c')
if 0 in {x, y, z}: list1.append('d')
if 0 in {x, y, z}: list1.append('e')
if 0 in {x, y, z}: list1.append('f') print(list1)
# ['c', 'd', 'e', 'f']</pre>
<p>This solution is the same as the above solution with Tuples. The only difference is the data structure that we use here. With this solution we perform membership checks using Sets and based on the condition being True or False, appending the respective alphabet “c”, “d”, “e”, “f” to list1.</p>
<p>I hope this explanation helps. Try and get your hands dirty running the above code snippets, and you will have a better understanding by the time you are done.</p>
<h2>Author</h2>
<p>This article is contributed by Finxter Abhigyan Ojha. <a href="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/" target="_blank" rel="noreferrer noopener" title="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/">You can find his Upwork profile here.</a></p></p>
</div>


https://www.sickgaming.net/blog/2020/06/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016