![]() |
|
[Tut] The Most Pythonic Way to Check if Two Ordered Lists Are Identical - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] The Most Pythonic Way to Check if Two Ordered Lists Are Identical (/thread-95883.html) |
[Tut] The Most Pythonic Way to Check if Two Ordered Lists Are Identical - xSicKxBot - 06-25-2020 The Most Pythonic Way to Check if Two Ordered Lists Are Identical The most Pythonic way to check if two ordered lists Code: l1Code: l2Code: l1 == l2Code: True![]() Problem: Given are two lists Code: l1Code: l2Code: TrueCode: TrueCode: FalseExamples: Code: 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) --> TrueLet’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview: https://trinket.io/embed/python/349ed3ed5b Exercise: Glance over all methods and run the code. What questions come to mind? Do you understand each method? Read on to learn about each method in detail! Method 1: Simple Comparison Not always is the simplest method the best one. But for this particular problem, it is! The equality operator Code: ==Code: # 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))
# FalseSo, if you just want to learn about the most Pythonic way to solve this problem, look no further. But if you want to dive into the wonderful world of Python, learning about different interesting and powerful Python functions, read on! Method 2: Simple For Loop The following method is what you’d see from a coder coming from another programming language or from a beginner who doesn’t know about the equality operator on lists (see Method 1). Code: # 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))
# FalseIn 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: l1[i] != l2[i]Code: FalseIf you went through the whole loopwithout returning Code: FalseCode: len(l1) == len(l2)Code: TrueA lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the Code: zip()Method 3: zip() + For Loop The zip functiontakes 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. Let’s see how you can use the function to make the previous code more concise: Code: # 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))
# FalseInstead 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()Method 4: sum() + zip() + len() But true Python coders will often avoid a for loop and use a generator expression instead.
Code: # 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]))
# TrueFrom the methods except the first one using the Code: ==Code: zip(), len(), and sum()You could also write this in a single line of code! Code: sum(x == y for x, y in zip(l1, l2)) == len(l1) == len(l2)If you love Python one-liners, check out my new book Python One-Liners with internationally renowned publisher NoStarch press. (Amazon Link) Method 5: map() + reduce() + len() The last method is just to train your functional programming skills. Code: # 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]))
# TrueThe Code: map()Code: reduce()Code: andCode: all()Method 6: map() + all() This is the same as the previous method—but using the Code: all()Code: reduce()Code: # 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]))
# TrueThanks for reading this article to the end! I hope you learned something new today. If you want to learn something new every day, join my free Python email series for continuous improvement in Python and computer science. Where to Go From Here? Enough theory, let’s get some practice! 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? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? 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. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |