Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] The Most Pythonic Way to Check if Two Ordered Lists Are Identical

#1
The Most Pythonic Way to Check if Two Ordered Lists Are Identical

<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="The Most Pythonic Way to Check if Two Ordered Lists Are Identical" width="1400" height="788" src="https://www.youtube.com/embed/RkLh-6ylaUg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p class="has-luminous-vivid-amber-background-color has-background">The most Pythonic way to check if two ordered lists <code>l1</code> and <code>l2</code> are identical, is to use the <code>l1 == l2</code> operator for element-wise comparison. If all elements are equal and the length of the lists are the same, the return value is <code>True</code>. </p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/probform-1024x576.jpg" alt="" class="wp-image-10085" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/probform-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p><strong>Problem</strong>: Given are two <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">lists </a><code>l1</code> and <code>l2</code>. You want to perform <em>Boolean Comparison</em>: Compare the lists element-wise and return <code>True</code> if your comparison metric returns <code>True</code> for all pairs of elements, and otherwise <code>False</code>.</p>
<p><strong>Examples</strong>:</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="">l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 5, 4]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 4, 5]
# compare(l1, l2) --> True</pre>
<p>Let’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview:</p>
<p> <iframe src="https://trinket.io/embed/python/349ed3ed5b" width="100%" height="1000" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Glance over all methods and run the code. What questions come to mind? Do you understand each method?</em></p>
<p>Read on to learn about each method in detail!</p>
<h2>Method 1: Simple Comparison</h2>
<p>Not always is the simplest method the best one. But for this particular problem, it is! The equality operator <code>==</code> compares a list <a href="https://blog.finxter.com/python-numpy-element-wise-multiplication/" target="_blank" rel="noreferrer noopener" title="[Numpy * Operator] Element-wise Multiplication in Python">element-wise</a>—many Python coders don’t know this!</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="">
# 1. Simple Comparison
def method_1(l1, l2): return l1 == l2 l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_1(l1, l2))
# False</pre>
<p>So, if you just want to learn about the most Pythonic way to solve this problem, look no further. </p>
<p>But if you want to dive into the <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener" title="Python Programming Tutorial [+Cheat Sheets]">wonderful world of Python</a>, learning about different interesting and powerful <a href="https://blog.finxter.com/python-cheat-sheet-functions-and-tricks/" target="_blank" rel="noreferrer noopener" title="Python Functions and Tricks Cheat Sheet">Python functions</a>, read on!</p>
<h2>Method 2: Simple For Loop</h2>
<p>The following method is what you’d see from a coder coming from another <a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" target="_blank" rel="noreferrer noopener" title="Python vs Go – Which Language You Should Choose">programming language</a> or from a beginner who doesn’t know about the equality operator on lists (see <strong>Method 1</strong>). </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=""># 2. Simple For Loop
def method_2(l1, l2): for i in range(min(len(l1), len(l2))): if l1[i] != l2[i]: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_2(l1, l2))
# False
</pre>
<p>In the code, you iterate over all indices from 0 to the last position of the smallest list as determined by the part <code>min(len(l1), len(l2))</code>. You then check if both elements at the same position are different. If they are different, i.e., <code>l1[i] != l2[i]</code>, you can immediately return <code>False</code> because the lists are also different. </p>
<p>If you went through the whole <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop </a>without returning <code>False</code>, the list elements are similar. But one list may still be longer! So, by returning <code>len(l1) == len(l2)</code>, you ensure to only return <code>True</code> if (1) all elements are equal and (2) the lists have the same length.</p>
<p>A lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the <code>zip()</code> function to reduce the <a href="https://blog.finxter.com/complexity-of-python-operations/" target="_blank" rel="noreferrer noopener" title="Complexity of Python Operations">complexity </a>of the code.</p>
<h2>Method 3: zip() + For Loop</h2>
<p><em>The <a href="https://blog.finxter.com/zip-unzip-python/" target="_blank" rel="noreferrer noopener" title="Zip &amp; Unzip: How Does It Work in Python?">zip function </a>takes a number of iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple for every i.</em></p>
<p>Let’s see how you can use the function to make the previous code more concise:</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="">
# 3. Zip + For Loop
def method_3(l1, l2): for x, y in zip(l1, l2): if x != y: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_3(l1, l2))
# False
</pre>
<p>Instead of iterating over indices, you now iterate over pairs of elements (the ones zipped together). If the lists have different sizes, the remaining elements from the longer list will be skipped. This way, element-wise comparison becomes simpler and no elaborate indexing schemes are required. Avoiding indices by means of the <code>zip()</code> function is a more Pythonic way for sure!</p>
<h2>Method 4: sum() + zip() + len()</h2>
<p>But true Python coders will often avoid a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener">for loop</a> and use a <a href="https://blog.finxter.com/how-to-use-generator-expressions-in-python-dictionaries/" title="How to Use Generator Expressions in Python Dictionaries" target="_blank" rel="noreferrer noopener">generator expression</a> instead. </p>
<ul>
<li>You first create an iterable of Boolean values using the generator expression <code>x == y for x, y in zip(l1, l2)</code>. </li>
<li>Then, you <a href="https://blog.finxter.com/python-sum-list/" title="Python sum() List – A Simple Illustrated Guide" target="_blank" rel="noreferrer noopener">sum </a>up over the Boolean values (another trick of pro coders) to find the number of elements that are the same and store it in variable <code>num_equal</code>. </li>
<li>Finally, you compare this with the length of both lists. If all three values are the same, both lists have the same elements and their length is the same, too. They are equal!</li>
</ul>
<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="">
# 4. Sum + Zip + Len
def method_4(l1, l2): num_equal = sum(x == y for x, y in zip(l1, l2)) return num_equal == len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_4(l1, l2))
# False print(method_4([1, 2], [1, 2]))
# True
</pre>
<p>From the methods except the first one using the <code>==</code> operator, this is the most Pythonic way due to the use of efficient Python helper functions like <code><a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" title="Python Ziiiiiiip! [A helpful guide]">zip()</a>, <a href="https://blog.finxter.com/python-list-length-whats-the-runtime-complexity-of-len/" target="_blank" rel="noreferrer noopener" title="Python List Length – What’s the Runtime Complexity of len()?">len()</a>, and <a href="https://blog.finxter.com/python-sum-list/" target="_blank" rel="noreferrer noopener" title="Python sum() List – A Simple Illustrated Guide">sum()</a></code> and generator expressions to make the code more concise and more readable. </p>
<p>You could also write this in a <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">single line</a> of code!</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="">sum(x == y for x, y in zip(l1, l2)) == len(l1) == len(l2)</pre>
<p><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener">If you love Python one-liners, check out my new book<strong> Python One-Liners</strong> with internationally renowned publisher NoStarch press.</a> (Amazon Link)</p>
<h2>Method 5: map() + reduce() + len()</h2>
<p>The last method is just to train your <a href="https://blog.finxter.com/the-reduce-function-is-dead-long-live-the-reduce-function/" title="The Reduce Function is Dead. Long Live the Reduce Function!" target="_blank" rel="noreferrer noopener">functional programming</a> skills. </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="">
# 5. map() + reduce() + len()
from functools import reduce
def method_5(l1, l2): equal = map(lambda x, y: x == y, l1, l2) result = reduce(lambda x, y: x and y, equal) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True
</pre>
<p>The <a href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank" rel="noreferrer noopener" title="How to Get Rid of Python’s Map Function With List Comprehension"><code>map()</code> function</a> combines all pairs of elements to Boolean values (are the two elements equal?). The<code> re<a href="https://blog.finxter.com/about-guidos-fate-of-reduce-in-python-3000/" target="_blank" rel="noreferrer noopener" title="About Guido’s Article: “Fate of Reduce() in Python 3000”">duce()</a></code> function combines all Boolean values performing an <code>and</code> operation. Sure, you can also use the more concise variant using the <code>all()</code> function:</p>
<h2>Method 6: map() + all()</h2>
<p>This is the same as the previous method—but using the <a href="https://blog.finxter.com/how-to-apply-a-logical-operator-to-all-elements-in-a-python-list/" target="_blank" rel="noreferrer noopener" title="{AND, OR, NOT} How to Apply Logical Operators to All List Elements in Python?"><code>all()</code> function</a> instead of <code>reduce()</code> to combine all Boolean values in a global <strong><em>and </em></strong>operation.</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=""># 6. map() + all()
def method_6(l1, l2): result = all(map(lambda x, y: x == y, l1, l2)) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True</pre>
<p>Thanks for reading this article to the end! I hope you learned something new today. If you want to learn something new every day, <a href="https://blog.finxter.com/subscribe/" title="Subscribe" target="_blank" rel="noreferrer noopener">join my free Python email series</a> for continuous improvement in Python and computer science. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/06/...identical/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016